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.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

14 lines
Python 3.9+
import 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

stdout
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

  1. Use `shutil.copyfile` for content-only copying without any metadata.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.