python在記憶體中產生Zip檔案!

來源:互聯網
上載者:User

import zipfile

import StringIO

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')

 

to everyone: 2013,Happy New Year!!!!!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.