How to Create a Zip File in Python


In this article, we show how to create a zip file in Python.

A zip file is a file that is composed of compressed files and folders. This helps reduce the overall file size.

Python has a module named the zipmodule module that allows us to work with zip files, including creating zip files, reading zip files, and extracting all files and folders from zip files.

So using Python, we can take files on our computer or within the internet directory being worked with and have them compressed into a zip file.

This is done using the write() function and specifying the files that you want in a zip file within this function.

We show this in the code below.

So the first thing we need to do is import the zipfile module.

Again, this is the module that allows us to work and do functions on zip files.

We import the os module just to show the current working directory that we are working with, where the zip file is located and where the extracted files will be.

We then create a variable, myzipfile, which is created to hold a zipfile object.

The full line of code is, myzipfile= zipfile.ZipFile('', 'a')

This line of code creates a zip file called ''

This line of code also specifies the mode to open the file with. The mode we chose is 'a'. 'a' stands for append. This mode appends files to the file. If you chose to use the 'w' mode, which stands for the write mode. This will erase all files in the file. Therefore, unless you want to do this, it is better to use the append mode.

So after running this line of code, you should see within the current working directory you are working with a zip file named ''

This file will first be empty.

The next step is to begin adding files to this newly created zip file.

We do this with the write() function.

The first parameter we pass to the write() function is the file that we want to add to the zip file. This will add the compressed version of the file to the zip file.

The second parameter we pass into the write function is the compression type., which specifies the algorithm to use to for the file compression. This can always just be set to, compress_type=zipfile.ZIP_DEFLATED

This will add the doc1.txt file to the zip file.

If you attempt to look inside this zip file, access will be denied, at least on most Windows PC, because we haven't yet closed the zipfile object in our Python program. All after you close this zipfile object will access be allowed to the zip file.

We then add doc2.txt, doc3.txt, and doc4.txt to the zip file.

We then must close the zipfile object.

Now we can open the zip file.

And this is how we can create and add files to a zip file in Python.

Related Resources

How to Extract All Files and Folders from a Zip File in Python
How to Read the Contents of a Zip File in Python

HTML Comment Box is loading comments...