The example Ethier provided has several problems, some of them major:
- doesn't work for real data on Windows. A ZIP file is binary and its data should always be written with a file opened 'wb'
- the ZIP file is appended to for each file, this is inefficient. It can just be opened and kept as an
InMemoryZip
attribute
- the documentation states that ZIP files should be closed explicitly, this is not done in the append function (it probably works (for the example) because zf goes out of scope and that closes the ZIP file)
- the create_system flag is set for all the files in the zipfile every time a file is appended instead of just once per file.
- on Python < 3 cStringIO is much more efficient than StringIO
- doesn't work on Python 3 (the original article was from before the 3.0 release, but by the time the code was posted 3.1 had been out for a long time).
An updated version is available if you install ruamel.std.zipfile
(of which I am the author). After
pip install ruamel.std.zipfile
or including the code for the class from here, you can do:
import ruamel.std.zipfile as zipfile
# Run a test
zipfile.InMemoryZipFile()
imz.append("test.txt", "Another test").append("test2.txt", "Still another")
imz.writetofile("test.zip")
You can alternatively write the contents using imz.data
to any place you need.
You can also use the with
statement, and if you provide a filename, the contents of the ZIP will be written on leaving that context:
with zipfile.InMemoryZipFile('test.zip') as imz:
imz.append("test.txt", "Another test").append("test2.txt", "Still another")
because of the delayed writing to disc, you can actually read from an old test.zip
within that context.