2 min read

Python Shutil Module

The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal.

Importing the Module

import shutil

Copying Files

shutil.copy()

Copies the file src to the file or directory dst. Permissions are copied, but metadata like creation time might not be.

import shutil

shutil.copy('source.txt', 'destination.txt')

shutil.copy2()

Identical to copy(), but attempts to preserve file metadata (timestamps, etc.).

shutil.copy2('source.txt', 'destination.txt')

Copying Directories

shutil.copytree()

Recursively copies an entire directory tree rooted at src to a directory named dst. The destination directory must not already exist.

import shutil

shutil.copytree('source_folder', 'destination_folder')

Moving and Renaming

shutil.move()

Recursively moves a file or directory (src) to another location (dst). This is effectively a rename if on the same filesystem.

import shutil

shutil.move('source.txt', 'new_folder/source.txt')

Deleting Directories

shutil.rmtree()

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory).

import shutil

# Be careful! This deletes everything inside the folder.
shutil.rmtree('folder_to_delete')

Archiving

The shutil module provides high-level utilities to create and read compressed archive files (zip, tar, etc.).

Creating an Archive

import shutil

# Create a zip file 'backup.zip' from the directory 'data'
shutil.make_archive('backup', 'zip', 'data')

Unpacking an Archive

import shutil

shutil.unpack_archive('backup.zip', 'extracted_folder')

Disk Usage

Get disk usage statistics about the given path.

import shutil

total, used, free = shutil.disk_usage("/")

print(f"Total: {total // (2**30)} GiB")
print(f"Used: {used // (2**30)} GiB")
print(f"Free: {free // (2**30)} GiB")

programming/python/python