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中title()方法的使用简介

 title()方法返回所有单词的第一个字符大写的字符串的一个副本。 语法 以下是title()方法的语法: str.title(); 参数  &nb...

使用Python代码实现Linux中的ls遍历目录命令的实例代码

使用Python代码实现Linux中的ls遍历目录命令的实例代码

一、写在前面   前几天在微信上看到这样一篇文章,链接为:https://www.jb51.net/it/692145.html,在这篇文章中,有这样一段话,吸引了我的注意:      ...

python安装numpy和pandas的方法步骤

最近要对一系列数据做同比比较,需要用到numpy和pandas来计算,不过使用python安装numpy和pandas因为linux环境没有外网遇到了很多问题就记下来了。首要条件,pyt...

python制作mysql数据迁移脚本

用python写了个数据迁移脚本,主要是利用从库将大的静态表导出表空间,载导入到目标实例中。 #!/usr/bin/env python3 #-*- coding:utf8 -*-...

基于Python检测动态物体颜色过程解析

基于Python检测动态物体颜色过程解析

本篇文章将通过图片对比的方法检查视频中的动态物体,并将其中会动的物体定位用cv2矩形框圈出来。本次项目可用于树莓派或者单片机追踪做一些思路参考。寻找动态物体也可以用来监控是否有人进入房间...