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调用java的jar包方法

如下所示: from jpype import * jvmPath = getDefaultJVMPath() jars = ["./Firstmaven-1.0-SNAPSHO...

Python实现合并excel表格的方法分析

本文实例讲述了Python实现合并excel表格的方法。分享给大家供大家参考,具体如下: 需求 将一个文件夹中的excel表格合并成我们想要的形式,主要要pandas中的concat()...

Python检测网站链接是否已存在

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。 Python由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。 像Perl语言...

Python中实现结构相似的函数调用方法

python的dict用起来很方便,可以自定义key值,并通过下标访问,示例如下: 复制代码 代码如下: >>> d = {'key1':'value1', ... '...

django框架F&Q 聚合与分组操作示例

本文实例讲述了django框架F&Q 聚合与分组操作。分享给大家供大家参考,具体如下: F 使用查询条件的值,专门取对象中某列值的操作,可以对同一个表中的两个列进行比较 from d...