shutil ModuleThe shutil (shell utilities) module in Python provides high-level functions for working with files, directories, and archives. It builds on top of the lower-level os module and makes common tasks like copying, moving, deleting folders, and creating backups much simpler and safer.
Use shutil whenever you need to:
copy(), copytree(), move(), rmtree() abstract away OS-specific details.copy() vs copy2() differ in whether they also copy metadata (timestamps, permissions).copytree() and rmtree() recursively process directories.make_archive() and unpack_archive() help create and extract compressed backups.disk_usage() gives total, used, and free space for a given path.shutil.copyfile(src, dst) – copy contents of one file to another.shutil.copy(src, dst) – copy file + permissions.shutil.copy2(src, dst) – copy file + metadata (timestamps, etc.).shutil.copytree(src, dst, dirs_exist_ok=False) – recursively copy an entire directory tree.shutil.move(src, dst) – move or rename files/directories.shutil.rmtree(path) – delete a directory tree (even if not empty).shutil.make_archive(base_name, format, root_dir)shutil.unpack_archive(filename, extract_dir=None)shutil.disk_usage(path)(total, used, free) bytes.
import shutil
from pathlib import Path
source = Path("data/report.txt")
destination = Path("backup/report.txt")
# Ensure parent directory exists
destination.parent.mkdir(parents=True, exist_ok=True)
# copy2 copies file contents + metadata (timestamps, permissions)
shutil.copy2(source, destination)
print("Backup created at:", destination)
import shutil
src_dir = "project_v1"
dst_dir = "project_backup"
# Copy entire directory tree recursively
# dirs_exist_ok=True (Python 3.8+) allows destination to exist
shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True)
print("Project copied to:", dst_dir)
import shutil
# base_name: path without extension
# format: "zip", "tar", "gztar", "bztar", "xztar"
# root_dir: directory to archive
archive_path = shutil.make_archive(
base_name="backups/source_code_backup",
format="zip",
root_dir="src"
)
print("Archive created at:", archive_path)
import shutil
# Get disk usage statistics for the root directory
usage = shutil.disk_usage("/")
# Convert byte values to gigabytes for easier reading
total_gb = usage.total / (1024 ** 3)
used_gb = usage.used / (1024 ** 3)
free_gb = usage.free / (1024 ** 3)
# Print a simple disk space report
print(f"Total: {total_gb:.2f} GB")
print(f"Used : {used_gb:.2f} GB")
print(f"Free : {free_gb:.2f} GB")
copy2():
backup/) is created if it does not exist.copy2() copies the file contents and metadata.copytree():
project_v1 are copied to project_backup.dirs_exist_ok=True, the destination can already exist (Python 3.8+).make_archive():
src folder is compressed into a ZIP file named source_code_backup.zip inside backups/.archive_path tells you exactly where the zip is stored.disk_usage():
shutilpathlib.Path with shutil for cleaner, cross-platform path handling.copy2() over copy() when metadata matters (e.g., backups, logs).rmtree() – it permanently deletes directories (including contents).try/except around file operations to handle missing files or permission errors.shutilimportant_docs into a backups/ folder with the current date in the folder name.copytree() to create a snapshot of your current coding project before you start a risky refactor.logs/ folder into a ZIP file at the end of each day using make_archive().disk_usage().rmtree(), but only after asking for confirmation in the terminal.You can run these scripts from the command line with: python your_script_name.py