zip is a popular compression format and algorithm used to compress files and folders. Python provides the
zipfile module in order to work with zipped files. A zip file contains single or more files and folders in a compressed way with lossless compression.
The zip file operations are provided with the
zipfile module in Python. The zipfile module provides different methods and attributes about zip files and related objects. In order to work with zip files, the zipfile module should be imported like below.
Extract Single File
Single file from the zip file can be extracted by using the
open() method which opens the file inside the zip file.
import zipfile zf = zipfile.ZipFile("my.zip") f = zf.open("cities.txt") print(f.name) f.read()
Extract Zip File
The zipfile module provides the
extractall() method which can be used to extract all files and folders. In the following example, we extract the contents of the
my.zip in the current working directory. By default, the extractall() method overwrites existing files.
import zipfile zf = zipfile.ZipFile("my.zip") zf.extractall()
List Zip File Contents As List
A zip file may contain single or multiple files and folders. These files and folders can be listed as a list type by using the
namelist() method like below.
import zipfile zf = zipfile.ZipFile("my.zip") zf.namelist()
['cities.txt', 'MyFile.csv', 'numbers.txt']
List Zip File Contents and Information
A zip file may contain multiple files and folders. These files and folders have different information and attribute like filename, compress_type, filemode, file_size, compress_size, etc.
import zipfile zf = zipfile.ZipFile("my.zip") zf.infolist()