Copy a file in Python
This post will discuss how to copy a file in Python.
There are several ways to copy files in Python. The most common and efficient ones are discussed below in detail:
1. Using shutil.copy2() function
The shutil module offers several high-level functions to support the copying and removal of files. You can use the copy2(src, dst) function to copy the file src to the file or directory dst.
1. If dst is a file name, the content and file metadata of src are copied. If dst is an existing file, it will be overwritten by the src file.
|
1 2 3 4 5 |
src = '/src/file.txt' dest = '/dest/log.txt' shutil.copy2(src, dest) |
2. If dst specifies a directory, we’ll copy the src file into the directory dst. If a file with the same name already exists in the destination location, it will get overwritten.
|
1 2 3 4 5 |
src = '/src/file.txt' dest = '/dest/dir' shutil.copy2(src, dest) |
The major advantage of copy2() is that it can accept a target directory path and also copies the file metadata. You can also use the copy() function identical to the copy2() function, except it fails to preserve the metadata.
The shutil module also has the copyfile(src, dst) function, which copies the contents of the file named src to a target file named dst. No metadata is copied. However, it overwrites the destination file if it already exists.
|
1 2 3 4 5 |
src = '/src/file.txt' dest = '/dest/log.txt' shutil.copyfile(src, dest) |
2. Using Path.write_bytes() function
Starting with Python 3.4, you can use the pathlib module, which offers classes representing object-oriented file system paths. It has the Path.write_bytes() function, which opens the file pointed to in bytes mode, write data to it, and close the file. No exchange of file metadata happens here. This overwrites the file if it already exists in the destination’s location.
|
1 2 3 4 5 6 |
from pathlib import Path src = Path('/src/file.txt') dest = Path('/dest/log.txt') dest.write_bytes(src.read_bytes()) |
3. Using open() function
Finally, you can open the source file in reading mode ('r') and write its contents to the destination file opened in the write mode ('w'). The write mode opens the file for writing after truncating it and create one if it does not exist.
|
1 2 3 4 5 6 7 8 9 |
src = '/src/file.txt' dest = '/dest/log.txt' with open(src, 'r') as f: data = f.read() with open(dest, 'w') as f: f.write(data) |
That’s all about copying a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)