Python2: (contains compression options, if only packaged, you can adjust the zipfile. zip_deflated)
Import Zipfileimport Stringioclass Inmemoryzip (object): Def __init__ (self): # Create the in-memory file-like obj ECT 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 so that # 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 = in Memoryzip () imz.append ("/home/test/1.jpg", Imagebuf) imz.writetofile ("Test.zip")
Python3: (Contains package options, not compressed)
Import Zipfileimport Ioclass Inmemoryzip (object): def __init__ (self): self.in_memory_zip = io. Bytesio () def append (self, filename_in_zip, file_contents): ZF = ZipFile. ZipFile (Self.in_memory_zip, "a", ZipFile. zip_stored, False) zf.writestr (Filename_in_zip, file_contents) for zfile in zf.filelist: zfile.create_ System = 0 return self- def read1 (self): self.in_memory_zip.seek (0) return Self.in_memory_zip.read ( ) def writetofile (self, filename): f = open (filename, "WB") F.write (Self.read1 ()) f.close () if __ name__ = = "__main__": Imz = Inmemoryzip () f1 = open ('/home/yangbing/jpg/1.jpg ', ' RB '). Read () Imz.append ("1.jpg", F1) F2 = open ('/home/yangbing/jpg/2.jpg ', ' RB '). Read () imz.append ("2.jpg", F2) Imz.writetofile ("Test.zip")
Python2/python3 in-memory Package/compress files