python使用内存zipfile对象在内存中打包文件示例
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")
上一篇: 高中英语老师
下一篇: 刚才和母上大人一起出去逛街