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

yipeiwu_com5年前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利用正则表达式匹配并截取指定子串及去重的方法

本文实例讲述了Python利用正则表达式匹配并截取指定子串及去重的方法。分享给大家供大家参考。具体如下: import re pattern=re.compile(r'\| (\d+...

python文件特定行插入和替换实例详解

python文件特定行插入和替换实例详解 python提供了read,write,但和很多语言类似似乎没有提供insert。当然真要提供的话,肯定是可以实现的,但可能引入insert会带...

Python 中的lambda函数介绍

Lambda函数,即Lambda 表达式(lambda expression),是一个匿名函数(不存在函数名的函数),Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambd...

python3.5实现socket通讯示例(TCP)

python3.5实现socket通讯示例(TCP)

TCP连接: tcp是面向连接的一个协议,意味着,客户端和服务器开发发送数据之前,需要先握手创建一个TCP连接。TCP连接的一端与客户端套接字相互联系,另一端与服务器套接字相联系。当创建...

python搜索包的路径的实现方法

查看python搜索包的路径的实现方法: python搜索包的路径存储在sys.path下 查看方法: import sys sys.path 临时添加python搜索包路径的方法: 方...