Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 258
user984003 Avatar asked Aug 27 '13 05:08

user984003


People also ask

How do I zip a memory in Python?

According to the Python docs: class zipfile. ZipFile(file[, mode[, compression[, allowZip64]]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. So, to open the file in memory, just create a file-like object (perhaps using BytesIO).

Is ZIP file included in Python?

Yes! Python has several tools that allow you to manipulate ZIP files. Some of these tools are available in the Python standard library. They include low-level libraries for compressing and decompressing data using specific compression algorithms, such as zlib , bz2 , lzma , and others.

How do I use ZIP file?

To zip (compress) a file or folder Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.


1 Answers

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

like image 180
falsetru Avatar answered Oct 05 '22 21:10

falsetru