Python's shutil Module Explained 🧰
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/copy2to copy files,moveto move or rename filescopytree/rmtreeto handle entire directoriesdisk_usagefor easy disk space calculationsmake_archive/unpack_archiveto handle archives
Comments
Post a Comment