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.
shutil.copyfile(src_file_path, dest_file_path)
The src_file_path
argument contains the file path of the source file whose contents are going to be copied.
The dest_file_path
argument contains the file path of the destination file where the contents are going to be pasted.
A “Permission denied” error occurs when the user cannot execute a command because they don’t have sufficient privileges.
Let’s discuss an example of reproducing this bug and then learn how to fix it.
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")
Line 1: We import the copyfile
function from the shutil
module
Line 6: Then, we use the copyfile
function to copy source.txt
to dest.txt
.
After running this code, the “Permission denied” error is thrown because we have stripped the user write permission for the dest.txt
file.
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")
Line 1–2: We import the copyfile
function from the shutil
module and also import the os
module.
Line 7: We use the copyfile
function to copy contents from source2.txt
to dest2.txt
.
Line 10: Finally, we use the os.system
function to view the contents of the dest2.txt
file.