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.
import shutil shutil.copyfile('sample.txt', 'sample1.txt')
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.
This will copy the contents of the source file to the destination file.
The following two type of exceptions are commonly encountered with this method. They are,
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.
import shutil shutil.copyfile('my_file.txt', 'copy.txt')
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 exists in different directory, give the filename as absolute path like this.
import shutil shutil.copyfile('home/text_files/my_file.txt', 'copy.txt')
The next common type of exception is the SameFileError. This will occur if the source file and the destination files have the same name.
import shutil shutil.copyfile('hello.txt', 'hello.txt')
The above code will generate the following error on the console.