Working with ZIP archives
- import zipfile
- class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True)
If you try to open a file that is not a ZIP file, the exception
zipfile.BadZipFile is raised.
In Python 2.7, this was spelled
zipfile.BadZipfile, and this old name is retained alongside the new one in Python 3.2+
Creating new archives
To create new archive open zipfile with write mode.
To add files to this archive use write() method.
If you want to write string of bytes into the archive you can use writestr() method.
Examining Zipfile Contents
There are a few ways to inspect the contents of a zipfile. You can use the
printdir to just get a variety of information sent to
We can also get a list of filenames with the
namelist method. Here, we simply print the list:
namelist, we can call the
infolist method, which returns a list of
ZipInfo objects, which contain additional information about each file, for instance a timestamp and file size:
Extracting zip file contents to a directory
Extract all file contents of a zip file
If you want extract single files use extract method, it takes name list and path as input parameter
Opening Zip Files
To start, import the
zipfile module, and set the filename.
Working with zip archives is very similar to working with files, you create the object by opening the zipfile, which lets you work on it before closing the file up again.
In Python 2.7 and in Python 3 versions higher than 3.2, we can use the
with context manager. We open the file in "read" mode, and then print a list of filenames: