Python's shutil Module Explained 🧰

Copy file icon

Python's shutil Module Explained 🧰

The shutil module provides a high-level interface for performing various file and directory operations, such as copying, moving, archiving, and checking disk usage.

1. Copying and Moving Files

import shutil

# Copy a single file
shutil.copy('source.txt', 'dest.txt')

# Copy file with metadata
shutil.copy2('source.txt', 'backup/source_backup.txt')

# Move or rename files
shutil.move('old.txt', 'new_folder/renamed.txt')

2. Copying and Removing Directories

import shutil

# Copy entire directory
shutil.copytree('src_folder', 'dst_folder')

# Remove entire directory
shutil.rmtree('dst_folder')

3. Checking Disk Usage

import shutil

total, used, free = shutil.disk_usage('/')
print(f"Total: {total // (2**30)}GB, Used: {used // (2**30)}GB, Free: {free // (2**30)}GB")

4. Creating and Extracting Archives

import shutil

# Create zip archive
shutil.make_archive('backup', 'zip', 'src_folder')

# Extract zip archive
shutil.unpack_archive('backup.zip', 'extract_folder')

Summary

  • copy/copy2 to copy files, move to move or rename files
  • copytree/rmtree to handle entire directories
  • disk_usage for easy disk space calculations
  • make_archive/unpack_archive to handle archives

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices 📝