The easiest way to copy a file in Python programming is to use the shutil module. shutil library provides several high level file related operations. For file copy operations you can use one of the several methods like shutil.copyfile, shutil.copyfileobj, shutil.copy or shutil.copy2. These methods have several differences and can be used in different occasions. You can read more about them here. New we will see the most advanced copy method shutil.copy2. This method copies the file to it’s destination and returns the new path. In addition, it also tries to preserver all the metadata, access permissions and the modification time of the file. Here is an example.
Copy file using shutil.copy2
The syntax for copy2 is copy2(source_file, [destination_file or destination_directory]).
from shutil import copy2 new_directory = copy2("samples/myfile.txt", "samples/folder01") print("\n", new_directory, "\n")
More file operation tips
- More about shutil and it’s copy methods at Python docs.