Skip to content

Python: Create Zip files

In Python, you can create zip files using the zipfile module, which is part of the standard library. Here’s an example of how you can create a zip file containing multiple files

import zipfile
import os

# List of file paths to include in the zip
files_to_zip = ['file1.txt', 'file2.txt', 'folder/file3.txt']

# Name for the resulting zip file
zip_file_name = 'my_archive.zip'

# Create a ZipFile object in write mode
with zipfile.ZipFile(zip_file_name, 'w') as zipf:
    # Add each file to the zip
    for file in files_to_zip:
        # Add the file to the zip with the same name or specify another name
        zipf.write(file, os.path.basename(file))

print(f"Zip file created: {zip_file_name}")

Explanation:

  • files_to_zip is a list containing paths to the files you want to include in the zip. Adjust it according to your files.
  • zip_file_name is the name you want to give to your resulting zip file.

The zipfile.ZipFile object is created in write mode using a context manager (with statement). It then iterates through each file in the files_to_zip list and adds them to the zip using zipf.write(file, os.path.basename(file)).

This code will create a zip file named my_archive.zip containing the specified files. Adjust the file paths and names according to your requirements.

Ensure that you have proper permissions to access the files you want to zip and have write permissions for the directory where you want to create the zip file.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments