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")

相关文章

Django rest framework实现分页的示例

Django rest framework实现分页的示例

第一种分页PageNumberPagination 基本使用 (1)urls.py urlpatterns = [ re_path('(?P<version>...

python非递归全排列实现方法

刚刚开始学习python,当前看到了函数这一节。结合数组操作,写了个非递归的全排列生成。原理是插入法,也就是在一个有n个元素的已有排列中,后加入的元素,依次在前,中,后的每一个位置插入,...

Python实现大数据收集至excel的思路详解

一、在工程目录中新建一个excel文件 二、使用python脚本程序将目标excel文件中的列头写入,本文省略该部分的code展示,可自行网上查询 三、以下code内容为:实现从接口获取...

50行Python代码获取高考志愿信息的实现方法

50行Python代码获取高考志愿信息的实现方法

最近遇到个任务,需要将高考志愿信息保存成Excel表格,BOSS丢给我一个网址表格之后就让我自己干了。虽然我以前也学习过Python编写爬虫的知识,不过时间长了忘了,于是摸索了一天之后终...

python opencv实现证件照换底功能

python opencv实现证件照换底功能

本文实例为大家分享了python opencv实现证件照换底功能的具体代码,供大家参考,具体内容如下 思路:先转到HSV空间,利用颜色提取背景制作掩模版mask,然后通过按位操作提取人像...