How to fix “Permission denied” error when using shutil.copyfile
Function definition
shutil is a Python module with many functions to perform high-level operations on files. One such function is shutil.copyfile that is used to copy contents from a source file to a destination file.
Syntax
shutil.copyfile(src_file_path, dest_file_path)
The
src_file_pathargument contains the file path of the source file whose contents are going to be copied.The
dest_file_pathargument contains the file path of the destination file where the contents are going to be pasted.
Error description
A “Permission denied” error occurs when the user cannot execute a command because they don’t have sufficient privileges.
Error diagnosis
Let’s discuss an example of reproducing this bug and then learn how to fix it.
Reproducing the error
Here, we have removed user read and write permissions from the source.txt file and the dest.txt file, respectively. If we run this code and attempt to use the shutil.copyfile function to copy the contents of source.txt to dest.txt, it will throw the “Permission denied” error.
from shutil import copyfile# To copy source.txt to dest.txtcopyfile("source.txt","dest.txt")
Code explanation
Line 1: We import the
copyfilefunction from theshutilmoduleLine 6: Then, we use the
copyfilefunction to copysource.txttodest.txt.
After running this code, the “Permission denied” error is thrown because we have stripped the user write permission for the dest.txt file.
Error resolution
We can resolve this error quite easily by providing read and write permissions for the user for both of the files. This can be achieved through different ways for each type of
On Windows, we can run the terminal as an Administrator, which will grant us full access to the files, and then we run the Python script from within the terminal.
On Linux/Mac, we can issue the following command to grant the user read-write privileges to both files.
chmod +rw source.txt dest.txt
The chmod command is used to change file access permissions for the user. The first argument +rw grants read and write permissions to the user, while the second and third arguments represent the files to which the permissions are granted.
Finally, after granting read-write access to the user, we rename the files to source2.txt and dest2.txt respectively, and run the Python script successfully. Lastly, the code prints the new contents of the dest2.txt file.
from shutil import copyfileimport os# To copy source.txt to dest.txtcopyfile("source2.txt","dest2.txt")# To view the new contents of dest2.txtos.system("cat dest2.txt")
Code explanation
Line 1–2: We import the
copyfilefunction from theshutilmodule and also import theosmodule.Line 7: We use the
copyfilefunction to copy contents fromsource2.txttodest2.txt.Line 10: Finally, we use the
os.systemfunction to view the contents of thedest2.txtfile.
Free Resources