Python uses memory ZipFile objects to package files in memory sample _python

Source: Internet
Author: User

Copy Code code 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 been created on Windows so
# 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.