Python uses a memory zipfile object to package files in the memory. Example

Source: Internet
Author: User
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 ")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.