The zipfile Module

(New in 2.0) The zipfile module allows you to read and write files in the popular ZIP archive format.

Listing the Contents

To list the contents of an existing archive, you can use the namelist and infolist methods used in Example 5-20. The former returns a list of filenames, and the latter returns a list of ZipInfo instances.

Example 5-20. Using the zipfile Module to List Files in a ZIP File

File: zipfile-example-1.py

import zipfile

file = zipfile.ZipFile("samples/sample.zip", "r")

# list filenames
for name in file.namelist():
    print name,
print

# list file information
for info in file.infolist():
    print info.filename, info.date_time, info.file_size

sample.txt sample.jpg
sample.txt (1999, 9, 11, 20, 11, 8) 302
asmple.jpg (1999, 9, 18, 16, 9, 44) 4762

Reading Data from a ZIP File

To read data from an archive, simply use the read method used in Example 5-21. It takes a filename as an argument and returns the data as a string.

Example 5-21. Using the zipfile Module to Read Data from a ZIP File

File: zipfile-example-2.py

import zipfile

file = zipfile.ZipFile("samples/sample.zip", "r")

for name in file.namelist():
    data = file.read(name)
    print name, len(data), repr(data[:10])

sample.txt 302 'We will pe'
sample.jpg 4762 '\377\330\377\340\000\020JFIF'

Writing Data to a ZIP File

Adding files to an archive is easy. Just pass the filename, and the name you want that file to have in the archive, to the write method.

The script in Example 5-22 creates a ZIP file containing all ...

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.