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实现App自动签到领取积分功能

Python实现App自动签到领取积分功能

要自动签到,最简单的是打开页面分析请求,然后我们用脚本实现请求的自动化。但是发现食行没有页面,只有 APP,这不是一个好消息,这意味着需要抓包处理了。 下面的操作就好办了,在电脑端的...

tensorflow 重置/清除计算图的实现

调用tf.reset_default_graph()重置计算图 当在搭建网络查看计算图时,如果重复运行程序会导致重定义报错。为了可以在同一个线程或者交互式环境中(ipython/jupy...

在Python中利用Into包整洁地进行数据迁移的教程

在Python中利用Into包整洁地进行数据迁移的教程

动机 我们花费大量的时间将数据从普通的交换格式(比如CSV),迁移到像数组、数据库或者二进制存储等高效的计算格式。更糟糕的是,许多人没有将数据迁移到高效的格式,因为他们不知道怎么(或者不...

python print 按逗号或空格分隔的方法

1)按,分隔 a, b = 0, 1 while b < 1000: print(b, end=',') a, b = b, a+b 1,1,2,3,5,8,13,...

Python实现XML文件解析的示例代码

1. XML简介 XML(eXtensible Markup Language)指可扩展标记语言,被设计用来传输和存储数据,已经日趋成为当前许多新生技术的核心,在不同的领域都有着不同的应...