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函数式编程学习之yield表达式形式详解

前言 yield的英文单词意思是生产,刚接触Python的时候感到非常困惑,一直没弄明白yield的用法。最近又重新学习了下,所以整理了下面这篇文章,供自己和大家学习参考,下面话不多说了...

用Pytorch训练CNN(数据集MNIST,使用GPU的方法)

听说pytorch使用比TensorFlow简单,加之pytorch现已支持windows,所以今天装了pytorch玩玩,第一件事还是写了个简单的CNN在MNIST上实验,初步体验的确...

在Python中使用正则表达式的方法

正则表达式(regular expression)是一种用形式化语法描述的文本匹配模式。在需要处理大量文本处理的应用中有广泛的使用,我没使用的编辑器,IDE中的搜索常用正则表达式作为搜索...

python放大图片和画方格实现算法

本文实例为大家分享了python放大图片和画方格的具体代码,供大家参考,具体内容如下 1、Python 放大图片和画方格算法 #!C:/Python27 # -*- coding:...

Python 时间操作例子和时间格式化参数小结

1.取过去具体时间的方法:复制代码 代码如下:#!/usr/bin/python   import time  #取一天前的当前具体时间 &nb...