Skip to content

Python read zip file without extracting

  • by

Use the ZipFile function with reading mode to reads zip files without extracting them in Python.

Python reads zip files without extracting

Simple example code reading contents of a zip file without extracting.

namelist() returns a list of all items in an archive recursively.

import zipfile

f = 'file01.zip'
z = zipfile.ZipFile(f, "r")
zinfo = z.namelist()
fi1 = ""

for name in zinfo:
    with z.open(name) as f1:
        fi1 = f1.readlines()
for line in fi1:
    print(line)

Output:

Python reads zip files without extracting

The /r/n character is the newline character in windows. The b’ character you see is related to python and how it parses the file.

How can I read the contents of this zip file which should give the same output as the original file?

Use print(line.decode('ascii').strip()) instead of print(line)

Do comment if you have any doubts or suggestions on this Python zipfile topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading