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函数修饰符@的使用方法解析

python函数修饰符@的作用是为现有函数增加额外的功能,常用于插入日志、性能测试、事务处理等等。 创建函数修饰符的规则: (1)修饰符是一个函数 (2)修饰符取被修饰函数为参数...

浅谈Python 递归算法指归

浅谈Python 递归算法指归

1. 递归概述 递归( recursion)是一种编程技巧,某些情况下,甚至是无可替代的技巧。递归可以大幅简化代码,看起来非常简洁,但递归设计却非常抽象,不容易掌握。通常,我们都是自上...

python编写猜数字小游戏

python编写猜数字小游戏

本文实例为大家分享了python编写猜数字小游戏的具体代码,供大家参考,具体内容如下 import random secret = random.randint(1, 30)...

解决pandas 作图无法显示中文的问题

解决pandas 作图无法显示中文的问题

最近开始使用 pandas 处理可视化数据,挖掘信息。但是在作图时遇到,无法显示中文的问题。 下面这段代码是统计 fujian1.csv 文件中 City 所在列中各个城市出现次数的代码...

对Python3之进程池与回调函数的实例详解

进程池 代码演示 方式一 from multiprocessing import Pool def deal_task(n): n -= 1 return n if __...