python使用内存zipfile对象在内存中打包文件示例

yipeiwu_com6年前Python基础

复制代码 代码如下:

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 that
        # 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")

相关文章

Python数据可视化 pyecharts实现各种统计图表过程详解

Python数据可视化 pyecharts实现各种统计图表过程详解

1、pyecharts介绍 Echarts是一款由百度公司开发的开源数据可视化JS库,pyecharts是一款使用python调用echarts生成数据可视化的类库,可实现柱状图,折...

python利用socketserver实现并发套接字功能

python利用socketserver实现并发套接字功能

本文实现利用python的socketserver这个强大的模块实现套接字的并发,具体内容如下 目录结构如下: 测试文件请放在server_file文件夹里面 server.py...

详解Python的Django框架中inclusion_tag的使用

另外一类常用的模板标签是通过渲染 其他 模板显示数据的。 比如说,Django的后台管理界面,它使用了自定义的模板标签来显示新增/编辑表单页面下部的按钮。 那些按钮看起来总是一样的,但是...

Python之列表实现栈的工作功能

问题: python中使用列表实现栈的功能 """ 栈的工作原理 入栈 出栈 查看栈顶元素 栈的长度 栈是否为空 """ stack = [] info = ""...

matlab中实现矩阵删除一行或一列的方法

实例如下所示: >> A=[1,2,3;4,5,6;7,8,9] A = 1 2 3 4 5 6 7 8 9 删除行: >> A...