Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Open file in zip without temporarily extracting it

Tags:

python

zipfile

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

like image 829
user2880847 Avatar asked Oct 15 '13 01:10

user2880847


People also ask

Can Python access zipped files?

Python can work directly with data in ZIP files. You can look at the list of items in the directory and work with the data files themselves. This recipe is a snippet that lists all of the names and content lengths of the files included in the ZIP archive zipfile. zip .

How do I extract a single file from a ZIP file?

To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.


1 Answers

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.

like image 180
Jellema Avatar answered Sep 20 '22 13:09

Jellema