Copy files using python

Photo by Laika Notebooks on Unsplash

This article is about copying the contents of one file to another using python. This is possible with the help of a built-in python library called shutil. This library just copies the contents of the source file to the destination file in a single line of code.

How does it work?

The shutil module has a method called copyfile(). This method takes the source file name and the destination file name as the parameters. The copy of the source file is made in the same directory as the program unless a complete path is given as the destination file name.

code

Note: Make sure the sample.txt is in the same directory as the python program. If not, give the absolute path as the file name.

example: home/projects/sample.txt

This will copy the contents of the source file to the destination file.

Exceptions

The following two types of exceptions are commonly encountered with this method. They are,

  1. FileNotFoundError
  2. SameFileError

1. FileNotFoundError

As the name suggests this error is raised when the source file does not exist. If this error occurs even if the source file exists, then try giving the absolute path instead of just giving the filename.

Since my_file.txt does not exist in my current directory I get the following error from the debugger.

If your python code and the file exist in different directories, give the filename an absolute path like this.

2. SameFileError

The next common type of exception is the SameFileError. This will occur if the source file and the destination files have the same name.

The above code will generate the following error on the console.

Conclusion

This method will be a much better approach to copy files than manually opening using “with” method, getting the data, and then writing the bytes data to the destination file.

Python Developer | Django Developer | Python Enthusiast