Reading Data from Zip File#

Question#

Reading the content from a zip file.

Solution#



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()

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