Skip to content

Python zipfile Module

  • by

Python zipfile Module is a standard library module intended to manipulate ZIP files. This module provides tools to create, read, write, append, and list a ZIP file.

from zipfile import ZipFile

ZipFile is a class of zipfile modules for reading and writing zip files. Here we import only the class ZipFile from the zipfile module.

Python zipfile module example

Simple example code.

Creating and Adding to ZIP Files

import zipfile

with zipfile.ZipFile('', 'w') as new_zip:
new_zip.write('somefile.txt', compress_type=zipfile.ZIP_DEFLATED)


Python zipfile module example

Reading ZIP files

import zipfile

with zipfile.ZipFile('') as example_zip:
spam_info = example_zip.getinfo('somefile.txt')
print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))



Extracting from ZIP Files

The extractall() method will extract all the contents of the zip file to the current working directory. Use the extract() method to extract any file by specifying its path in the zip file.

import zipfile

with zipfile.ZipFile('') as example_zip:

Do comment if you have any doubts or suggestions on this Python module topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

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