PYTHON如何在内存中生成ZIP文件

高洛峰
发布: 2016-10-18 14:52:15
原创
1916人浏览过

如题,代码如下:

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)

立即学习Python免费学习笔记(深入)”;

      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')
登录后复制
python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号