Series: Learning Python: A Comprehensive Beginner Level Tutorial Series 🚀

Python's shutil Module

Dive into the Python shutil module. Our comprehensive guide explains file operations, directory manipulation, and practical examples for efficient file management in Python
E
Edtoks2:51 min read

The shutil module in Python provides a high-level interface for file and directory operations. It simplifies many common file and directory tasks. Here are some methods and functionality of the shutil module along with examples:

1. Copying Files and Directories

shutil.copy(src, dst): Copy the file at src to dst.

shutil.copytree(src, dst): Recursively copy a directory and its contents from src to dst.

import shutil

# Copy a file
shutil.copy("source.txt", "destination.txt")

# Copy a directory
shutil.copytree("source_dir", "destination_dir")

 

2. Moving or Renaming Files and Directories:

shutil.move(src, dst): Move a file or directory from src to dst.

import shutil

# Rename a file
shutil.move("old_name.txt", "new_name.txt")

# Move a directory
shutil.move("source_dir", "destination_dir")

 

3. Removing Files and Directories:

shutil.rmtree(path): Recursively remove a directory and its contents.

import shutil

# Remove a directory and its contents
shutil.rmtree("directory_to_remove")

 

4. Archiving and Compressing Files:

shutil.make_archive(base_name, format[, root_dir[, base_dir]]): Create an archive (e.g., zip or tar) of files in base_dir.

shutil.unpack_archive(filename[, extract_dir[, format]]): Extract an archive into extract_dir.

import shutil

# Create a zip archive
shutil.make_archive("archive", "zip", root_dir="source_dir")

# Extract a zip archive
shutil.unpack_archive("archive.zip", extract_dir="extracted_dir")

 

5. File and Directory Information:

shutil.disk_usage(path): Get disk usage statistics for the given path.

shutil.which(cmd): Find the path to an executable in the system's PATH.

import shutil

disk_usage = shutil.disk_usage("/")
print("Disk Usage (Total):", disk_usage.total)

python_path = shutil.which("python")
print("Path to Python:", python_path)

 

6. File Permissions and Ownership:

shutil.copystat(src, dst): Copy permissions, timestamps, and other metadata from src to dst.

Note: Some systems may require elevated permissions for changing file ownership.

import shutil

# Copy permissions and metadata
shutil.copystat("src_file", "dst_file")

 

7. File and Directory Comparison:

shutil.compare_files(file1, file2): Compare two files and return True if they have the same content.

import shutil

if shutil.compare_files("file1.txt", "file2.txt"):
    print("Files are the same.")

These are some of the methods and functionality provided by the shutil module in Python. It's a valuable tool for managing files and directories in a Python script, making it easier to perform common file operations.