shutil | Python Standard Library – Real Python
The Python shutil module provides a higher-level interface for file operations, including copying and removal. It builds upon the capabilities of the os module. It’s particularly useful for managing files and directories.
Here’s a quick example:
Key Features
- Copies files and directories
- Moves files and directories
- Removes files and directories
- Archives and unarchives files
- Discovers available disk space
Frequently Used Classes and Functions
Examples
Move a file to a new directory:
Remove a directory and all its contents:
Common Use Cases
- Copying and moving files or directories
- Removing directories and their contents
- Creating archives of directories
- Checking disk space before performing file operations
Real-World Example
Suppose you want to organize a project by moving all .txt files from a source directory to a target directory and then creating a ZIP archive of the target directory:
This example demonstrates how to organize files and create a backup archive using the shutil module.
Tutorial
Working With Files in Python
In this tutorial, you'll learn how you can work with files in Python by using built-in modules to perform practical tasks that involve groups of files, like renaming them, moving them around, archiving them, and getting their metadata.
For additional information on related topics, take a look at the following resources: