当前位置: 移动技术网 > IT编程>脚本编程>Python > python使用内存zipfile对象在内存中打包文件示例

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

2019年03月30日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网