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 一行代码能实现丧心病狂的功能

Python 一行代码能实现丧心病狂的功能

手头有 109 张头部 CT 的断层扫描图片,我打算用这些图片尝试头部的三维重建。基础工作之一,就是要把这些图片数据读出来,组织成一个三维的数据结构(实际上是四维的,因为每个像素有 RG...

python获取指定字符串中重复模式最高的字符串方法

给定一个字符串,如何得到其中重复模式最高的子字符串,我采用的方法是使用滑窗机制,对给定的字符串切分,窗口的大小从1增加到字符串长度减1,将所有的得到的切片统计结果,在这里不考虑单个字符的...

Python之reload流程实例代码解析

本文研究的主要是Python之reload流程的相关内容,具体如下。 在Python中,reload() 用于重新载入之前载入的模块。 reload() 函数语法: reload(m...

在Python中操作文件之truncate()方法的使用教程

 truncate()方法截断该文件的大小。如果可选的尺寸参数存在,该文件被截断(最多)的大小。 大小默认为当前位置。当前文件位置不改变。注意,如果一个指定的大小超过了文件的当...

Python数据类型之Tuple元组实例详解

本文实例讲述了Python数据类型之Tuple元组。分享给大家供大家参考,具体如下: tuple元组 1.概述 本质上是一种有序的集合,和列表非常的相似,列表使用[]表示,元组使用()表...