How to Copy a File with shutil.copy2 in Python
Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.
Python code
14 linesimport shutil
from pathlib import Path
source = Path("sample.txt")
destination = Path("sample_copy.txt")
source.write_text("Hello, PythonSkillset!")
if __name__ == "__main__":
shutil.copy2(source, destination)
copied = destination.read_text()
print(f"Copied content: {copied}")
print(f"Source exists: {source.exists()}, Copy exists: {destination.exists()}")
print(f"Metadata preserved: {source.stat().st_mtime == destination.stat().st_mtime}")
Output
Copied content: Hello, PythonSkillset!
Source exists: True, Copy exists: True
Metadata preserved: True
How it works
shutil.copy2 copies both the content and metadata (permissions, timestamps) from the source to the destination. The pathlib.Path objects make it easy to reference and manipulate file paths. Wrapping the call in an if __name__ == "__main__" block lets the script run only when executed directly, not when imported. Calling stat().st_mtime on both paths verifies that the modification time was carried over. Using Path.write_text creates the source file in a quick, readable way for testing.
Common mistakes
- Using `shutil.copy` when you need metadata like timestamps preserved — it doesn't copy them.
- Forgetting that `copy2` overwrites the destination file if it already exists.
- Not checking that the source file exists before copying, which raises `FileNotFoundError`.
Variations
- Use `shutil.copyfile` for content-only copying without any metadata.
- Use `shutil.copystat` separately to copy metadata to an already-created file.
Real-world use cases
- Backing up uploaded user files while keeping their original modification times intact.
- Duplicating configuration or asset files in a build process where timestamps matter.
- Replicating files to a staging directory while preserving attributes for deployment checks.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.