Search code examples
pythonzipstringio

Python, write in memory zip to file


How do I write an in memory zipfile to a file?

# Create in memory zip and add files
zf = zipfile.ZipFile(StringIO.StringIO(), mode='w',compression=zipfile.ZIP_DEFLATED)
zf.writestr('file1.txt', "hi")
zf.writestr('file2.txt', "hi")

# Need to write it out
f = file("C:/path/my_zip.zip", "w")
f.write(zf)  # what to do here? Also tried f.write(zf.read())

f.close()
zf.close()

Solution

  • StringIO.getvalue return content of StringIO:

    >>> import StringIO
    >>> f = StringIO.StringIO()
    >>> f.write('asdf')
    >>> f.getvalue()
    'asdf'
    

    Alternatively, you can change position of the file using seek:

    >>> f.read()
    ''
    >>> f.seek(0)
    >>> f.read()
    'asdf'
    

    Try following:

    mf = StringIO.StringIO()
    with zipfile.ZipFile(mf, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr('file1.txt', "hi")
        zf.writestr('file2.txt', "hi")
    
    with open("C:/path/my_zip.zip", "wb") as f: # use `wb` mode
        f.write(mf.getvalue())