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:
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
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.
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
>>> shutil.copy2('file1.txt', 'file2.txt')