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('new.zip', 'w') as new_zip:
new_zip.write('somefile.txt', compress_type=zipfile.ZIP_DEFLATED)
Output:
Reading ZIP files
import zipfile
with zipfile.ZipFile('new.zip') as example_zip:
print(example_zip.namelist())
spam_info = example_zip.getinfo('somefile.txt')
print(spam_info.file_size)
print(spam_info.compress_size)
print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))
Output:
['somefile.txt']
44
43
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('new.zip') as example_zip:
example_zip.extractall()
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.