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
- Import
shutil. - Use
shutil.copy2()to preserve metadata,shutil.move()to relocate, andshutil.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 likecp -p; it preserves permissions, timestamps, and flags.copytree()acceptsignorecallbacks 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()raisesFileExistsErrorif the destination exists; usedirs_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.