How do I copy, move, and delete files with shutil in Python?

· Category: Python Programming

Short answer

The shutil module provides high-level file operations that build on top of os and os.path. It handles copying files and metadata, moving files, and removing entire directory trees.

Steps

  1. Import shutil.
  2. Use shutil.copy2() to preserve metadata, shutil.move() to relocate, and shutil.rmtree() to delete directories.
import shutil
from pathlib import Path

# Copy preserving metadata
shutil.copy2("source.txt", "backup/source.txt")

# Move
shutil.move("old_dir/file.txt", "new_dir/file.txt")

# Copy entire directory tree
shutil.copytree("project", "project_backup")

# Remove tree
shutil.rmtree("temp_folder")

Tips

  • copy2() is like cp -p; it preserves permissions, timestamps, and flags.
  • copytree() accepts ignore callbacks to skip files (e.g., ignore=shutil.ignore_patterns("*.pyc")).
  • shutil.disk_usage("/") reports free space, which is useful before large copy operations.

Common issues

  • rmtree() permanently deletes directories without sending them to a trash or recycle bin.
  • copytree() raises FileExistsError if the destination exists; use dirs_exist_ok=True (Python 3.8+) to merge.
  • Moving across filesystems falls back to copy-and-delete, which can be slow and may fail if the source is read-only.