How to copy files using shutil module in Python

The shutil module contains many functions but two of them can be used to copy files from one location to another. To demonstrate this, I created two text files as shown in the image below:

copy files with shutil

You can copy the content of the file1.txt to the file2.txt. This way, both files will have the same content but they will still have their original names.

>>> import shutil
>>> new_file_path = shutil.copy('file1.txt', 'file2.txt')

This will copy file1.txt to file2.txt, returning the path of file2.txt to the variable new_file_path. You can give as second parameter a directory name so the file will be copied into this directory under the original name.

copy files with shutil

Now the file2.txt says “This is file 1.”.

You could use copy2() instead of copy() to preserve the metadata associated with the file but the amount of the preserved metadata depends on the operating system and the platform used. In the worst case scenario the result will be as using copy().

>>> shutil.copy2('file1.txt', 'file2.txt')

Leave a Reply