Working with zip files in Python
Last Updated :
22 Jul, 2021
This article explains how one can perform various operations on a zip file using a simple python program.
What is a zip file?
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.
Why do we need zip files?
- To reduce storage requirements.
- To improve transfer speed over standard connections.
To work on zip files using python, we will use an inbuilt python module called zipfile.
1. Extracting a zip file
from zipfile import ZipFile
file_name = "my_python_files.zip"
with ZipFile(file_name, 'r') as zip:
zip.printdir()
print('Extracting all the files now...')
zip.extractall()
print('Done!')
|
The above program extracts a zip file named “my_python_files.zip” in the same directory as of this python script.
The output of above program may look like this:

Let us try to understand the above code in pieces:
-
from zipfile import ZipFile
ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module.
-
with ZipFile(file_name, 'r') as zip:
Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in 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.
For example:
zip.extract('python_files/python_wiki.txt')
This will extract only the specified file.
If you want to read some specific file, you can go like this:
data = zip.read(name_of_file_to_read)
2. Writing to a zip file
Consider a directory (folder) with such a format:

Here, we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file.
The following program does this by crawling the directory to be zipped:
from zipfile import ZipFile
import os
def get_all_file_paths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
def main():
directory = './python_files'
file_paths = get_all_file_paths(directory)
print('Following files will be zipped:')
for file_name in file_paths:
print(file_name)
with ZipFile('my_python_files.zip','w') as zip:
for file in file_paths:
zip.write(file)
print('All files zipped successfully!')
if __name__ == "__main__":
main()
|
The output of above program looks like this:

Let us try to understand above code by dividing into fragments:
-
def get_all_file_paths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
First of all, to get all file paths in our directory, we have created this function which uses the os.walk() method. In each iteration, all files present in that directory are appended to a list called file_paths.
In the end, we return all the file paths.
-
file_paths = get_all_file_paths(directory)
Here we pass the directory to be zipped to the get_all_file_paths() function and obtain a list containing all file paths.
-
with ZipFile('my_python_files.zip','w') as zip:
Here, we create a ZipFile object in WRITE mode this time.
-
for file in file_paths:
zip.write(file)
Here, we write all the files to the zip file one by one using write method.
3. Getting all information about a zip file
from zipfile import ZipFile
import datetime
file_name = "example.zip"
with ZipFile(file_name, 'r') as zip:
for info in zip.infolist():
print(info.filename)
print('\tModified:\t' + str(datetime.datetime(*info.date_time)))
print('\tSystem:\t\t' + str(info.create_system) + '(0 = Windows, 3 = Unix)')
print('\tZIP version:\t' + str(info.create_version))
print('\tCompressed:\t' + str(info.compress_size) + ' bytes')
print('\tUncompressed:\t' + str(info.file_size) + ' bytes')
|
The output of above program may look like this:

for info in zip.infolist():
Here, infolist() method creates an instance of ZipInfo class which contains all the information about the zip file.
We can access all information like last modification date of files, file names, system on which files were created, Zip version, size of files in compressed and uncompressed form, etc.
This article is contributed by Nikhil Kumar.
Similar Reads
Python Pillow - Writing Text on Image
In this article, we will see how to write text on images with the Python Pillow module. Installation This module is not preloaded with Python. So to install it execute the following command in the command-line: pip install pillow Stepwise implementation: Step 1: Import Pillow library To complete thi
6 min read
Scheduling Python Scripts on Linux
Sometimes we need to do a task every day, and we can do these repetitive tasks every day by ourselves, or we can use the art of programming to automate these repetitive tasks by scheduling the task. And today in this article we are going to learn how to schedule a python script on Linux to do the re
3 min read
Wand image.emboss in Python
Emboss effect is similar to Edge extraction but it is more like a 3d effect. The traditional use for Emboss is to make something look more three-dimensional by adding highlights and shadows to different parts of your layer. In order to generate an Embossed image we use emboss function in Wand. Simil
1 min read
PYGLET â Key Motion String
In this article, we will see how we can get the key motion string for the modifiers in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resource
3 min read
Python - Rounding button corners in kivy using .kv file
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article we will going to learn how to round the button co
4 min read
How to get sheet names using openpyxl - Python
The openpyxl library is widely used to handle excel files using Python. Often when dealing with excel files one might have noticed multiple sheets. The sheets are normally mentioned in the bottom left corner of the screen. One can install this library by running the following command. pip install op
2 min read
Python | Ways to iterate tuple list of lists
In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combi
3 min read
Python | sympy.fibonacci() method
With the help of sympy.fibonacci() method, we can find the Fibonacci number and Fibonacci polynomial in SymPy. fibonacci(n) - The Fibonacci numbers are the integer sequence defined by the initial terms [Tex]F_0 = 0 [/Tex], [Tex]F_1 = 1 [/Tex]and the two-term recurrence relation [Tex]F_n = F_{n-1} +
2 min read
Downloading PDFs with Python using Requests and BeautifulSoup
BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, yo
2 min read
Python PIL | ImageOps.flip() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of âready-madeâ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images. ImageOps.flip() Flip the
1 min read