pythonmemoryzipstringiopython-zipfile

Extracting a zipfile to memory?


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

Solution

  • 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()}