Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?

Tags:

python

I've written some Python code that fetches a zip file from the web and into a string:

In [1]: zip_contents[0:5]
Out[1]: 'PK\x03\x04\x14'

I see there's a zipfile library, but I'm having trouble finding a function in it that I can just pass a bunch of raw zip data. It seems to want to read it from a file.

Do I really need to dump this to a temp file, or is there a way around it?

like image 269
mike Avatar asked Aug 21 '09 19:08

mike


2 Answers

zipfile.ZipFile accepts any file-like object, so you can use StringIO (2.x) or BytesIO (3.x):

try:
  from cStringIO import StringIO
except:
  from StringIO import StringIO
import zipfile

fp = StringIO('PK\x03\x04\x14')
zfp = zipfile.ZipFile(fp, "r")
like image 145
John Millikin Avatar answered Sep 22 '22 01:09

John Millikin


Wrap your string in a cStringIO object. It looks, acts, and quacks like a file object, but resides in memory.

like image 35
Eevee Avatar answered Sep 22 '22 01:09

Eevee