欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python使用内存zipfile对象在内存中打包文件示例

程序员文章站 2022-05-31 15:07:56
复制代码 代码如下:import zipfileimport stringio class inmemoryzip(object):   ...

复制代码 代码如下:

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