Extracting a zipfile to memory?

user1438003 picture user1438003 · Jun 6, 2012 · Viewed 42.4k times · Source

How do I extract a zip to memory?

My attempt (returning None on .getvalue()):

from zipfile import ZipFile
from StringIO import StringIO

def extract_zip(input_zip):
    return StringIO(ZipFile(input_zip).extractall())

Answer

mata picture mata · Jun 6, 2012

extractall extracts to the file system, so you won't get what you want. To extract a file in memory, use the ZipFile.read() method.

If you really need the full content in memory, you could do something like:

def extract_zip(input_zip):
    input_zip=ZipFile(input_zip)
    return {name: input_zip.read(name) for name in input_zip.namelist()}