Python: Open file in zip without temporarily extracting it

user2880847 picture user2880847 · Oct 15, 2013 · Viewed 130.5k times · Source

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

Answer

Jellema picture Jellema · Oct 15, 2013

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.