Use shutil.copy2() (or shutil.copy()) from Python’s built-in shutil module to copy files reliably across Windows, macOS, and Linux. shutil.copy2() copies both the file’s contents and its metadata (such as modification timestamps and permissions), making it the closest Python equivalent to the shell cp -p command.
Basic Example
import shutil
# 1. Define source file and destination path (file path or target directory)
source = "reports/summary.pdf"
destination = "backup/summary_copy.pdf"
# 2. Copy the file while preserving metadata (timestamps, permissions)
copied_path = shutil.copy2(source, destination)
print(f"File copied to: {copied_path}")
Key Details & Alternative Methods
- Destination can be a directory or a full file path: If
destinationis an existing directory (e.g.,"backup/"),shutil.copy2()keeps the original filename ("backup/summary.pdf"). Ifdestinationincludes a filename, it renames the copy and overwrites any existing file at that path. - Working with
pathlib.Pathobjects: Allshutilcopy functions natively acceptPathobjects alongside plain strings:from pathlib import Path import shutil src = Path("data/input.csv") dst_dir = Path("archive") dst_dir.mkdir(exist_ok=True) shutil.copy2(src, dst_dir / src.name) - Copying without preserving timestamps (
shutil.copy()): If you want the copied file to receive the current system timestamp instead of retaining the original file’s creation/modification times, useshutil.copy(source, destination). - Copying entire directories (
shutil.copytree()): To recursively copy an entire folder and all its nested files, useshutil.copytree("src_folder", "dst_folder", dirs_exist_ok=True).
Comparison of shutil Copy Functions
| Function | Copies File Data | Copies Permissions | Copies Metadata (Timestamps) | Accepts Directory as Destination? |
|---|---|---|---|---|
shutil.copy2(src, dst) |
Yes | Yes | Yes | Yes |
shutil.copy(src, dst) |
Yes | Yes | No | Yes |
shutil.copyfile(src, dst) |
Yes | No | No | No (dst must be a full file path) |
shutil.copytree(src, dst) |
Yes (recursive) | Yes | Yes | Copies whole directory trees |
You must log in or register to comment.
