How to Create and Extract Zip File using Python

Hello Internet Programmer, Today we Create and Extract Zip File using Python. This article explains how one can perform various operations on a zip file using a simple python program.

ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data.

So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together.

So let’s do it.

Installation

No additional installation required. We are using an inbuilt python module called zipfile.

Code

Compress file to zip

import zipfile

zf = zipfile.ZipFile("codesnail.zip", "w")
zf.write("codesnail.txt", compress_type=zipfile.ZIP_DEFLATED)
zf.close()

#follow @code_snail on insta

Above code converts codesnail.txt into codesnail.zip and store in the current path where this program file exists.

zf=zipfile.ZipFile("codesnail.zip", "w")

The class for reading and writing ZIP files. See section ZipFile Objects for constructor details. Here we are open in write mode.

zf.write("codesnail.txt", compress_type=zipfile.ZIP_DEFLATED)

Here, we write all the files to the zip file one by one using the write method. If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. ZIP_DEFLATED is a compression method.

zf.close()

Close the archive file. You must call close() before exiting your program or essential records will not be written.

Extracting zip file

from zipfile import ZipFile

with ZipFile("codesnail.zip", "r") as zip:
    zip.printdir()
    zip.extractall()

# follow @code_snail

The above program extracts a zip file named codesnail.zip in the same directory as this python script.

with ZipFile("codesnail.zip", "r") as zip:

Here, a ZipFile object is made by calling ZipFile constructor which accepts the zip file name (file path) and mode parameters. We create a ZipFile object in the READ mode and name it as zip.

zip.printdir()

printdir() method prints a table of contents for the archive.

zip.extractall()

extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.

That’s it. This is the code for create and extract zip file using python.

Now it’s your turn to try this code and create and extract the zip file in python. Share it with your friends and happy coding :)

More python stuff,