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的fabric包完成代码上传部署

首先是安装fabric包 pip install fabric fabric常用参数 -l : 显示定义好的任务函数名 -f : 指定fab入口文件,默认入口文件名为fabfi...

PYTHON如何读取和写入EXCEL里面的数据

PYTHON如何读取和写入EXCEL里面的数据

好久没写了,今天来说说python读取excel的常见方法。首先需要用到xlrd模块,pip install xlrd 安装模块。 首先打开excel文件: xl = xlrd.open...

在NumPy中创建空数组/矩阵的方法

如何在NumPy中创建空数组/矩阵? 在添加行的情况下,你最好的选择是创建一个与数据集最终一样大的数组,然后向它添加数据 row-by-row: >>> impo...

python安装Scrapy图文教程

python安装Scrapy图文教程

安装方法 pip install Scrapy 如果顺利的话不用管直接一路下来就OK 验证是否安装成功 安装成功 不顺利的情况 1)lxml安装不成功 使用whl进行安装,不过需要先...

彻底理解Python list切片原理

关于list的insert函数 list#insert(ind,value)在ind元素前面插入value 首先对ind进行预处理:如果ind<0,则ind+=len(a),这样...