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+opencv识别图片中的圆形(霍夫变换)

详解利用python+opencv识别图片中的圆形(霍夫变换)

在图片中识别足球 先补充下霍夫圆变换的几个参数知识: dp,用来检测圆心的累加器图像的分辨率于输入图像之比的倒数,且此参数允许创建一个比输入图像分辨率低的累加器。上述文字不好理解的...

vc6编写python扩展的方法分享

系统环境:VC6 + Python-2.5.4 1、下载Python-2.5.4源码。 2、解压,打开D:\Python-2.5.4\PC\VC6\pcbuild.dsw,编译,D:\P...

小结Python用fork来创建子进程注意事项

自己随手写了Python下 fork 进程的测试代码(来说明这个问题不一定完全合适): def fork(a): def now(): import datetime re...

python实现八大排序算法(1)

python实现八大排序算法(1)

排序 排序是计算机内经常进行的一种操作,其目的是将一组”无序”的记录序列调整为”有序”的记录序列。分内部排序和外部排序。若整个排序过程不需要访问外存便能完成,则称此类排序问题为内部排序。...

Django1.9 加载通过ImageField上传的图片方法

这里假设你是通过models的ImageField上传图片,并期望在前台img标签中能显示。能否访问图片关键在于,是否能通过正确的路径访问。 在models.py中有image如下...