This article mainly introduces the example of using the memory zipfile object to package files in the memory in python. For more information, see the following code:
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
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 been created on Windows so that
# Unix permissions are 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 ")