The code is as follows:
Import ZipFile
Import Stringio
Class Inmemoryzip (object):
def __init__ (self):
# Create the In-memory File-like object
Self.in_memory_zip = Stringio.stringio ()
def append (self, filename_in_zip, file_contents):
"Appends a file with name Filename_in_zip and contents of
File_contents to the in-memory zip. "
# Get A handle to the In-memory zip in append mode
ZF = ZipFile. ZipFile (Self.in_memory_zip, "a", ZipFile. zip_deflated, False)
# Write The file to the In-memory zip
Zf.writestr (Filename_in_zip, file_contents)
# Mark the files as having a been created on Windows
# Unix permissions is not inferred as 0000
For Zfile in Zf.filelist:
Zfile.create_system = 0
return self
def read (self):
"Returns a string with the contents of the in-memory zip."
Self.in_memory_zip.seek (0)
Return Self.in_memory_zip.read ()
def writetofile (self, filename):
"' writes the in-memory zip to a file."
f = file (filename, "w")
F.write (Self.read ())
F.close ()
if __name__ = = "__main__":
# Run a test
Imz = Inmemoryzip ()
Imz.append ("Test.txt", "another Test"). Append ("Test2.txt", "Still another")
Imz.writetofile ("Test.zip")