Shutil Module in Python
The shutil module in Python offers high-level file operations such as copying, moving, renaming, deleting files and directories, checking disk space, handling archives like ZIP and TAR. It is useful for automating file system tasks.
1. Importing the shutil Module
Before using shutil, import it:
import shutil
2. Operations on Files
2.1 Copying Files
The shutil module offers several ways to copy files.
(i) shutil.copy(src, dst)
- Copies a file from
src(source) todst(destination). - If
dstis a directory the file is copied inside that directory. - It does not copy metadata (timestamps, permissions).
Example:
import shutil
# Copy file to a new file
shutil.copy("source.txt", "destination.txt")
# Copy file into a directory
shutil.copy("source.txt", "backup/")
Expected Output:
source.txt is copied to destination.txt
source.txt is copied to backup/source.txt
(ii) shutil.copy2(src, dst)
- Similar to
shutil.copy(), but preserves metadata.
Example:
shutil.copy2("source.txt", "backup/")
Expected Output:
source.txt is copied to backup/source.txt with timestamps and permissions preserved.
(iii) shutil.copyfile(src, dst)
- Copies only file contents (no metadata).
dstmust be a file (not a directory).
Example:
shutil.copyfile("source.txt", "destination.txt")
Expected Output:
source.txt is copied to destination.txt (contents only, no metadata).
(iv) shutil.copymode(src, dst)
- Copies only file permissions (not contents or timestamps).
Example:
shutil.copymode("source.txt", "destination.txt")
Expected Output:
Permissions of source.txt copied to destination.txt.
(v) shutil.copystat(src, dst)
- Copies metadata (timestamps, permissions, etc.) but not the contents.
Example:
shutil.copystat("source.txt", "destination.txt")
Expected Output:
Metadata (timestamps and permissions) copied from source.txt to destination.txt.
2.2 Copying Directories
(vi) shutil.copytree(src, dst, dirs_exist_ok=False)
- Recursively copies a directory and its contents to
dst. - If
dirs_exist_ok=True, it allows existing directories.
Example:
shutil.copytree("my_folder", "backup_folder")
Expected Output:
my_folder and its contents copied to backup_folder.
3. Moving Files and Directories
shutil.move(src, dst)
- Moves a file or directory from
srctodst. - If
dstis a directory,srcis moved inside.
Example:
shutil.move("old_location/file.txt", "new_location/")
Expected Output:
file.txt moved from old_location to new_location.
4. Deleting Files and Directories
shutil.rmtree(path)
- Deletes a directory and all its contents.
Example:
shutil.rmtree("folder_to_delete")
Expected Output:
folder_to_delete and its contents deleted permanently.
Warning: This action is permanent and cannot be undone.
5. Disk Usage and Space Information
shutil.disk_usage(path)
- Returns disk usage statistics (total, used, and free space).
Example:
import shutil
usage = shutil.disk_usage("/")
print(f"Total: {usage.total} bytes")
print(f"Used: {usage.used} bytes")
print(f"Free: {usage.free} bytes")
Expected Output:
Total: 500000000000 bytes
Used: 300000000000 bytes
Free: 200000000000 bytes
(The actual numbers will depend on your system.)
6. Archiving and Compression
(i) shutil.make_archive(base_name, format, root_dir)
- Creates an archive (ZIP, TAR, etc.) from a directory.
Example:
shutil.make_archive("backup", "zip", "my_folder")
Expected Output:
backup.zip created from my_folder.
(ii) shutil.unpack_archive(filename, extract_dir)
- Extracts an archive into a directory.
Example:
shutil.unpack_archive("backup.zip", "extracted_folder")
Expected Output:
backup.zip extracted to extracted_folder.
7. Temporary File Operations
shutil.which(cmd)
- Finds the path of an executable file.
Example:
print(shutil.which("python"))
Expected Output:
/usr/bin/python (or C:\Python39\python.exe on Windows)
(The actual output depends on your system.)
8. Full Backup Script
A script that:
- Copies a directory.
- Creates a compressed backup.
Example:
import shutil
# Define source and backup locations
src_folder = "my_data"
backup_folder = "backup"
# Copy the folder
shutil.copytree(src_folder, backup_folder, dirs_exist_ok=True)
# Create a compressed backup
shutil.make_archive("backup", "zip", backup_folder)
print("Backup completed successfully!")
Expected Output:
my_data copied to backup.
backup.zip created from backup folder.
Backup completed successfully!
Conclusion
The shutil module is a powerful tool for working with files and directories. It simplifies common operations such as copying, moving, deleting, and compressing files. Understanding these functions can help automate file management tasks efficiently.