How Can I Create a ZIP Archive of a Directory in Python?

Susan Sarandon
Release: 2024-11-19 01:45:02
Original
831 people have browsed it

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:

  • Output filename: The desired name and location of the ZIP archive.
  • Format: Specify "zip" for a ZIP archive.
  • Directory name: The path to the directory you wish to archive.

Here's an example:

import shutil
shutil.make_archive("my_archive", "zip", "/path/to/my_directory")
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template