PYTHON如何在記憶體中生成ZIP檔案

pythontab發表於2013-01-02

如題,程式碼如下:

class MemoryZipFile(object):
   def __init__(self):
       #建立記憶體檔案
       self._memory_zip = StringIO.StringIO()
       
   def append_content(self, filename_in_zip, file_content):
       """
       description: 寫文字內容到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:寫檔案內容到zip

      注意這裡的第二個引數是本地磁碟檔案的全路徑(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: 讀取zip檔案內容

      """

      self._memory_zip.seek(0)

      return self._memory_zip.read()

 

  def write_file(self, filename):

      """

      description:寫zip檔案到磁碟

      """

      f = file(filename, "wb")

      f.write(self.read())

      f.close()




使用方法如下:


        mem_zip_file = MemoryZipFile()
        mem_zip_file.append_content('mimetype', "application/epub+zip")
        mem_zip_file.append_content('META-INF/container.xml', '''<?xml version="1.0" encoding="UTF-8" ?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> </container>''');
        #追加磁碟上的檔案內容到記憶體,注意這裡的第二個引數是本地磁碟檔案的全路徑(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')


相關文章