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 读取摄像头数据并保存的实例

如下所示: import cv2 cap = cv2.VideoCapture(0) k = 0 while k != 27: # esc ret, img = cap.re...

Python多线程编程(四):使用Lock互斥锁

前面已经演示了Python:使用threading模块实现多线程编程二两种方式起线程和Python:使用threading模块实现多线程编程三threading.Thread类的重要函数...

实例说明Python中比较运算符的使用

实例说明Python中比较运算符的使用

下表列出了所有Python语言支持的比较操作符。假设变量a持有10和变量b持有20,则:  例如: 试试下面的例子就明白了所有的Python编程语言提供的比较操作符:...

python随机生成库faker库api实例详解

废话不多说,直接上代码! # -*- coding: utf-8 -*- # @Author : FELIX # @Date : 2018/6/30 9:49 from fake...

python基于opencv检测程序运行效率

这篇文章主要介绍了python基于opencv检测程序运行效率,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 涉及到的函数主要有两个:...