Python: Open file in zip without temporarily extracting it Python: Open file in zip without temporarily extracting it python python

Python: Open file in zip without temporarily extracting it


Vincent Povirk's answer won't work completely;

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

You have to change it in:

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

For details read the ZipFile docs here.


import io, pygame, zipfilearchive = zipfile.ZipFile('images.zip', 'r')# read bytes from archiveimg_data = archive.read('img_01.png')# create a pygame-compatible file-like object from the bytesbytes_io = io.BytesIO(img_data)img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.


In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:

import zipfilearchive = zipfile.ZipFile('images.zip', 'r')imgfile = archive.open('img_01.png')try:    image = pygame.image.load(imgfile, 'img_01.png')finally:    imgfile.close()