The shutil
module in Python provides a number of high-level operations on files and collections of files. It allows you to copy, move, remove, and manage files and directories in a simple way.
Here are some of the most commonly used functions in the shutil
module:
1. Copying Files
shutil.copy(src, dst)
: Copies the file fromsrc
todst
. The file’s content and its permissions are copied, but metadata like timestamps are not.shutil.copy2(src, dst)
: Similar tocopy
, but it also copies the file’s metadata (timestamps).shutil.copyfile(src, dst)
: Copies the contents of the file fromsrc
todst
, but does not copy metadata or permissions.shutil.copytree(src, dst)
: Recursively copies an entire directory tree fromsrc
todst
.
2. Moving Files
shutil.move(src, dst)
: Moves a file or directory fromsrc
todst
. If the destination is a directory, it will move the source into that directory.
3. Removing Files or Directories
shutil.rmtree(path)
: Removes an entire directory tree atpath
, including all its contents.shutil.remove(path)
: Removes a single file, just likeos.remove
.
4. Disk Usage and File Operations
shutil.disk_usage(path)
: Returns the disk usage statistics about the given path, including total, used, and free space.
5. Creating and Extracting Archives
shutil.make_archive(base_name, format, root_dir, ...)
: Creates an archive file (like.zip
,.tar
,.gztar
, etc.) from the contents of a directory.shutil.unpack_archive(filename, extract_dir)
: Extracts the contents of an archive (such as.zip
,.tar
, etc.) to a specified directory.
6. File Permissions and Ownership
shutil.chown(path, user=None, group=None)
: Changes the owner and/or group of the file or directory atpath
.
Example Usage:
import shutil
# Copying a file
shutil.copy('source.txt', 'destination.txt')
# Copying a directory tree
shutil.copytree('source_dir', 'destination_dir')
# Moving a file
shutil.move('source.txt', 'new_location.txt')
# Removing a directory tree
shutil.rmtree('old_dir')
# Getting disk usage
usage = shutil.disk_usage('/')
print(f'Total: {usage.total}, Used: {usage.used}, Free: {usage.free}')
# Creating an archive
shutil.make_archive('archive_name', 'zip', 'source_dir')
# Extracting an archive
shutil.unpack_archive('archive_name.zip', 'extract_dir')
Notes:
shutil
is part of the standard library, so you don’t need to install any external packages to use it.- Many functions in
shutil
can raise exceptions likeFileNotFoundError
orPermissionError
, so it’s good practice to handle these cases withtry
/except
blocks where necessary.
The shutil
module simplifies common file and directory operations, making it a powerful tool for file system management in Python.