Reading Data from Zip File

Question

Reading the content from a zip file.

Solution

from __future__ import print_function

import zipfile

def read_zip(filename):
    with zipfile.ZipFile(filename, 'r') as z:
        for zip_filename in z.namelist():
            print("File: {0}".format(zip_filename))
            _bytes = z.read(zip_filename)
            print("has {0} bytes".format(len(_bytes)))

def main():
    filename = 'sample.zip'
    read_zip(filename)

if __name__ == '__main__':
    main()
Run this

Explanation

We read the file with “r” permission instead of “rb”, as Python cookbook advises that it is more deterministic when running in Windows OS.

You can list the contents of the zipfile and then read few bytes of them as show in the example.

Here is a sample run of this program.

$zip -c sample.zip files_reading_zipfile.py

$ python files_reading_zipfile.py
File: files_reading_zipfile.py
has 406 bytes
Comments by Disqus