Home > Article > Backend Development > How Can I Create a ZIP Archive of a Directory in Python?
Creating ZIP Archive of a Directory in Python
Creating a compressed ZIP archive of a directory structure is a common task in software development and data management. Python provides multiple options to accomplish this, including the shutil module.
Using shutil.make_archive
The simplest way to create a ZIP archive of a directory is to utilize the shutil.make_archive function. This function supports both ZIP and TAR formats, making it versatile for various archiving needs.
To use shutil.make_archive, specify the following parameters:
Here's an example:
import shutil shutil.make_archive("my_archive", "zip", "/path/to/my_directory")
This command will create a ZIP archive named "my_archive.zip" in the current directory, containing the contents of the specified directory.
Exploring the zipfile Module
If you need more control over the archiving process, consider exploring the zipfile module. It provides lower-level access to create and manipulate ZIP archives, allowing you to customize options, skip certain files, and even add metadata.
For instance, to create a ZIP archive while excluding certain file patterns:
import zipfile with zipfile.ZipFile("my_archive.zip", "w") as zip: for root, dirs, files in os.walk("/path/to/my_directory"): for filename in files: if not filename.endswith(".txt"): zip.write(os.path.join(root, filename), filename)
This code iterates through files, skipping those with a ".txt" extension.
The above is the detailed content of How Can I Create a ZIP Archive of a Directory in Python?. For more information, please follow other related articles on the PHP Chinese website!