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 destination is an existing directory (e.g., "backup/"), shutil.copy2() keeps the original filename ("backup/summary.pdf"). If destination includes a filename, it renames the copy and overwrites any existing file at that path.
  • Working with pathlib.Path objects: All shutil copy functions natively accept Path objects 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, use shutil.copy(source, destination).
  • Copying entire directories (shutil.copytree()): To recursively copy an entire folder and all its nested files, use shutil.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