📂 shutil module
Last Updated: 25th August 2025
This module provides functions for copying, moving, and deleting files and directories.
List of Shutil Functions:
- shutil.copy(src, dst): Copies a file or directory from src to dst and keep file contents and its Permission.
import shutil
# Copy a file
src_file = "source_file.txt"
dst_file = "destination_file.txt"
shutil.copy(src_file, dst_file)
print(f"Copied {src_file} to {dst_file}")
# Copy a directory
src_dir = "source_directory"
dst_dir = "destination_directory"
shutil.copytree(src_dir, dst_dir)
print(f"Copied {src_dir} to {dst_dir}")
- shutil.copy2(src, dst):Like copy, but also copies metadata (timestamps, etc.).
import shutil
# Copy a file
src_file = "source_file.txt"
dst_file = "destination_file.txt"
shutil.copy2(src_file, dst_file)
print(f"Copied {src_file} to {dst_file}")
- shutil.copytree(src, dst): Copies an entire directory (including subfolders & files).
import shutil
# Copy a directory
src_dir = "source_directory"
dst_dir = "destination_directory"
shutil.copytree(src_dir, dst_dir)
print(f"Copied {src_dir} to {dst_dir}")
- shutil.move(src, dst): Moves a file or directory from src to dst.
import shutil
# Move a file
src_file = "source_file.txt"
dst_file = "destination_file.txt"
shutil.move(src_file, dst_file)
print(f"Moved {src_file} to {dst_file}")
- shutil.rmtree(path): Removes a directory and all its contents (⚠️ use carefully).
import shutil
# Remove a directory
dir_path = "directory_to_remove"
shutil.rmtree(dir_path)
print(f"Removed directory: {dir_path}")
- shutil.make_archive(base_name, format, root_dir): Creates a compressed archive (zip, tar, etc.).
import shutil
# Create an archive
base_name = "archive"
format = "zip"
root_dir = "directory_to_archive"
shutil.make_archive(base_name, format, root_dir)
print(f"Created archive: {base_name}.{format}")
- shutil.unpack_archive(archive, extract_dir): Extracts a compressed archive to a directory.
import shutil
# Extract an archive
archive = "archive.zip"
extract_dir = "extracted_directory"
shutil.unpack_archive(archive, extract_dir)
print(f"Extracted {archive} to {extract_dir}")
- shutil.disk_usage(path): Returns total, used, and free space of a disk.
import shutil
usage = shutil.disk_usage("/")
print(f"Total: {usage.total // (1024**3)} GB")
print(f"Used: {usage.used // (1024**3)} GB")
print(f"Free: {usage.free // (1024**3)} GB")