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+rsync精确同步指定格式文件

本文实例为大家分享了python+rsync精确同步指定格式文件的具体代码,供大家参考,具体内容如下 # coding: utf-8 #!/usr/bin/env python '...

在python中按照特定顺序访问字典的方法详解

最近使用python写一些东西,在参考资料的时候发现字典是没有顺序的,那么怎么样按照一定顺序访问字典呐,我找到了一个小方法: 假设一个字典是: D = {'a': '1', 'b':...

调用其他python脚本文件里面的类和方法过程解析

这篇文章主要介绍了调用其他python脚本文件里面的类和方法过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 问题描述: 自己编...

Python函数式编程指南(四):生成器详解

4. 生成器(generator) 4.1. 生成器简介 首先请确信,生成器就是一种迭代器。生成器拥有next方法并且行为与迭代器完全相同,这意味着生成器也可以用于Python的for循...

python中类的一些方法分析

本文实例分析了python中类的一些方法,分享给大家供大家参考。具体分析如下: 先来看看下面这段代码: class Super: def delegate(self):...