How to Copy a File in Python: Simple Guide with Examples
To copy a file in Python, use the
shutil.copy(src, dst) function from the shutil module, where src is the source file path and dst is the destination path. This copies the file content and permissions to the new location.Syntax
The basic syntax to copy a file in Python uses the shutil.copy function:
src: The path to the source file you want to copy.dst: The path where you want to copy the file to. It can be a directory or a full file path.
This function copies the file content and its permissions but not metadata like creation or modification times.
python
import shutil
shutil.copy(src, dst)Example
This example copies a file named example.txt to a new file called copy_example.txt in the same folder.
python
import shutil source_file = 'example.txt' destination_file = 'copy_example.txt' shutil.copy(source_file, destination_file) print(f'File copied from {source_file} to {destination_file}')
Output
File copied from example.txt to copy_example.txt
Common Pitfalls
Common mistakes when copying files include:
- Using a destination path that is a directory without a trailing slash or filename, which may cause errors or unexpected results.
- Trying to copy a file that does not exist, which raises a
FileNotFoundError. - Not having permission to read the source file or write to the destination folder, causing a
PermissionError.
Always check that the source file exists and you have the right permissions before copying.
python
import shutil # Wrong: destination is a directory without filename # shutil.copy('example.txt', 'destination_folder') # May copy with unexpected name # Right: specify full destination path shutil.copy('example.txt', 'destination_folder/example.txt')
Quick Reference
| Function | Description |
|---|---|
| shutil.copy(src, dst) | Copies file content and permissions from src to dst |
| shutil.copy2(src, dst) | Copies file content, permissions, and metadata (timestamps) |
| os.path.exists(path) | Checks if a file or folder exists at path |
| os.makedirs(path, exist_ok=True) | Creates directories if they don't exist |
Key Takeaways
Use shutil.copy(src, dst) to copy files easily in Python.
Ensure the source file exists and you have permission to read it.
Specify the full destination path including filename to avoid errors.
shutil.copy copies file content and permissions but not metadata.
Use shutil.copy2 if you want to copy metadata like timestamps too.