How python generates a zip file in memory

Source: Internet
Author: User
Title, the code is as follows:

Class Memoryzipfile (object):   def __init__ (self):       #创建内存文件       self._memory_zip = Stringio.stringio ()           def append_content (self, Filename_in_zip, file_content): "" "       Description: Write text content to zip" ""       ZF = ZipFile . ZipFile (Self._memory_zip, "a", ZipFile. zip_deflated, False)       zf.writestr (Filename_in_zip, file_content) for       Zfile in Zf.filelist:zfile.create_ System = 0       return self            def append_file (self, Filename_in_zip, Local_file_full_path): "" "       

Description: Write file contents to zip

Note that the second parameter here is the full path to the local disk file (Windows:c/demo/1.jpg | Linux:/usr/local/test/1.jpg)

"""

ZF = ZipFile. ZipFile (Self._memory_zip, "a", ZipFile. zip_deflated, False)

Zf.write (Local_file_full_path, Filename_in_zip)

For zfile in Zf.filelist:zfile.create_system = 0

return self

def read (self):

"""

Description: Reading the contents of a zip file

"""

Self._memory_zip.seek (0)

Return Self._memory_zip.read ()

def write_file (self, filename):

"""

Description: Write zip file to disk

"""

f = file (filename, "WB")

F.write (Self.read ())

F.close ()





Here's how to use it:

        Mem_zip_file = Memoryzipfile ()        mem_zip_file.append_content (' mimetype ', "Application/epub+zip")        Mem_zip_ File.append_content (' Meta-inf/container.xml ', '
 
  
 
   
 
  ");        #追加磁盘上的文件内容到内存, note that the second parameter here is the full path to the local disk file (Windows:c/demo/1.jpg | linux:/usr/local/test/1.jpg)        Mem_zip_file.append _file ("1.jpg", "c:\1.jpg")            #将内存中的zip文件写入磁盘        mem_zip_file.write_file ("C:test.zip")          #获取内存zip文件内容        data = Mem_zip_file.read ()          #上传到fdfs        my_fdfs_client.upload_by_buffer (data, ' 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.