python zip stringio
Updated Thu, 22 Sep 2022 03:30:01 GMT

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/", "w")
f.write(zf)  # what to do here? Also tried f.write(


StringIO.getvalue return content of StringIO:

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

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


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/", "wb") as f: # use `wb` mode

Comments (3)

External Links

External links referenced by this document: