September 11, 2024

Python shutil Module

The shutil module in Python provides a higher-level interface for file operations compared to the built-in os module. It offers functions for copying, moving, and deleting files and directories, as well as utilities for handling disk usage and archiving. The shutil module is useful for file management tasks and automating system administration processes.

1. File and Directory Operations

1.1 Copying Files

You can use the shutil.copy() and shutil.copy2() functions to copy files. The copy2() function also preserves the file’s metadata:

import shutil

# Copy a file
shutil.copy('source_file.txt', 'destination_file.txt')

# Copy a file with metadata
shutil.copy2('source_file.txt', 'destination_file.txt')
    

1.2 Copying Directories

The shutil.copytree() function copies an entire directory tree:

import shutil

# Copy an entire directory tree
shutil.copytree('source_directory', 'destination_directory')
    

1.3 Moving Files and Directories

You can move files and directories using the shutil.move() function:

import shutil

# Move a file or directory
shutil.move('source_file_or_directory', 'destination')
    

1.4 Removing Files and Directories

The shutil.rmtree() function is used to delete an entire directory tree:

import shutil

# Remove an entire directory tree
shutil.rmtree('directory_to_delete')
    

2. Disk Usage

The shutil.disk_usage() function provides information about disk usage:

import shutil

# Get disk usage statistics
usage = shutil.disk_usage('/')
print(f"Total: {usage.total}, Used: {usage.used}, Free: {usage.free}")
    

3. Archiving

The shutil module provides functions for creating and extracting archive files:

3.1 Creating Archives

You can create archives in formats like zip, tar, and gztar using the shutil.make_archive() function:

import shutil

# Create a zip archive
shutil.make_archive('archive_name', 'zip', 'directory_to_archive')
    

3.2 Extracting Archives

To extract archive files, you can use the shutil.unpack_archive() function:

import shutil

# Extract a zip archive
shutil.unpack_archive('archive_name.zip', 'destination_directory')
    

4. Working with File Descriptors

To work with file descriptors and file system operations, you can use shutil functions like shutil.chown() to change ownership:

import shutil

# Change file ownership
shutil.chown('file.txt', user='username', group='groupname')
    

5. Conclusion

The shutil module is a powerful tool for managing files and directories in Python. It provides a range of functions for copying, moving, deleting, and archiving files, as well as utilities for checking disk usage. Using shutil can simplify many file management tasks and improve automation in system administration scripts.