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实现对象列表根据某个属性排序的方法。分享给大家供大家参考,具体如下: 对于一个已有的python list, 里面的内容是一些对象,这些对象有一些相同的属性值,...

python UDP(udp)协议发送和接收的实例

需要建立2个文件,一个作为客户端,一个作为服务端 文件一 作为客户端client,文件二作为服务端server udp的特点是不需要建立连接 文件一客户端 #不需要建立连接 impo...

PyQt5实现简易电子词典

PyQt5是python中一个非常实用的GUI编程模块,功能十分强大。刚刚学完了Pyqt的编程,就迫不及待的写出了一个电子词典GUI程序。整个程序使用qt Desiner把整个gui界面...

python根据出生年份简单计算生肖的方法

本文实例讲述了python根据出生年份简单计算生肖的方法。分享给大家供大家参考。具体分析如下: 这里使用python根据出生年份计算生肖,看了代码会发现原来这么简单 #计算生肖 de...

python的绘图工具matplotlib使用实例

python的绘图工具matplotlib使用实例

matplotlib是功能十分强大的绘制二维图形的Python模块,它用Python语言实现了MATLAB画图函数的易用性,同时又有非常强大的可定制性。它提供了一整套和matlab相似的...