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+ffmpeg批量去视频开头的方法

用来批量切割视频的开头部分,比如去掉一部电视剧的序幕,看着难受不说数量还很多,很菜鸟的一篇,毕竟我也是一个菜鸟,首先要有ffmpeg这个软件,安装什么的就不说了,网上一搜就出来了,直接给...

Python中文件操作简明介绍

打开文件 open函数返回一个文件对象,基本语法: ●file_object = open(file_name, access_mode='r'[,buffering=-1]) file...

Python的Flask开发框架简单上手笔记

最简单的hello world #!/usr/bin/env python # encoding: utf-8 from flask import Flask app = Fla...

python实现给scatter设置颜色渐变条colorbar的方法

python实现给scatter设置颜色渐变条colorbar的方法

python设置scatter颜色渐变的方法 参考代码如下: <span style="font-size:18px;">import matplotlib.pyplot...

django 常用orm操作详解

Django流程: 1 创建Django项目 : django-admin startproject projectname 2 创建应用: : python manage.py sta...