Fix Python – Python: Open file in zip without temporarily extracting it

Question

Asked By – user2880847

How can I open files in a zip archive without extracting them first?

I’m using pygame. To save disk space, I have all the images zipped up.
Is it possible to load a given image directly from the zip file?
For example:
pygame.image.load('zipFile/img_01')

Now we will see solution for issue: Python: Open file in zip without temporarily extracting it


Answer

Vincent Povirk’s answer won’t work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

This question is answered By – Jellema

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0