Python, write in memory zip to file

user984003 picture user984003 · Aug 27, 2013 · Viewed 24.7k times · Source

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

Answer

falsetru picture falsetru · Aug 27, 2013

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