AppDividend
Latest Code Tutorials

How to Zip Multiple Files in Python

0

Python zipfile is an inbuilt module that helps us to zip files. To zip the file means we can reduce the file size. The size of the file size will be reduced after zipping the file.

ZIP is an archive file format that supports lossless data compression. The lossless data compression is a type of compression algorithm that allows the original data to be entirely rebuilt from the compressed data.

How to Zip Multiple Files in Python

To zip multiple files in Python, use the zipfile.ZipFile() method. Iterate all the files that need to be zipped and use the write() method to write the final zipped file. Let’s understand this example step by step.

Step 1: Define three zip files.

To zip multiple files, we first have to define three files. Let’s say we have the following three files in our project directory.

  1. purchase.csv
  2. sales.csv
  3. marketing.csv

Step 2: Import the zipfile module and create a list.

To import any module in Python, use the import statement.

# app.py

import zipfile

The next step is to create a list and add these three csv files as list items.

list_files = ['sales.csv', 'purchase.csv', 'marketing.csv']

Step 3: Open file using Python with.

Python With Statement is used to open files. It would help if you used “with statement” because it guarantees that open file descriptors are closed automatically after program execution completes.

with zipfile.ZipFile('final.zip', 'w') as zipF:
    for file in list_files:
        zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)

In this code, we have used with statement to open a final.zip file in the write mode. In the next step, we used for loop to iterate the files and write the one by one file in the zip mode. Means zip the one by one file, and the final output will be the final.zip file.

See the following complete code.

# app.py

import zipfile

list_files = ['sales.csv', 'purchase.csv', 'marketing.csv']

with zipfile.ZipFile('final.zip', 'w') as zipF:
    for file in list_files:
        zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)

print('The three files has been compressed')

Now, run the file.

python3 app.py
The three files has been compressed

Now check your project directory, and you can see that one file called final.zip is created. It is a zip file consists of three csv files.

That is it for this tutorial.

See also

Python unzip

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.