# !user/bin/env python3# -*-coding : utf-8 -*-import zipfile
from io import BytesIO
import os
classInMemoryZIP(object):def__init__(self):# create the in-memory file-like object
self.in_memory_zip = BytesIO()defappend(self, filename_in_zip, file_contents):""" Appends a file with name filename_in_zip \
and contents of file_contents to the in-memory zip.
"""# create a handle to the in-memory zip in append mode\ifnotisinstance(file_contents,bytes):
file_contents =bytes(str(file_contents), encoding='utf-8')
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 0000for zfile in zf.filelist:
zfile.create_system =0return self
defappendfile(self, file_path, file_name=None):""" Read a file with path file_path \
and append to in-memory zip with name file_name.
"""if file_name isNone:
file_name = os.path.split(file_path)[1]
f =open(file_path,'rb')
file_contents = f.read()
self.append(file_name, file_contents)
f.close()return self
defread(self):""" Returns a string with the contents of the in-memory zip.
"""
self.in_memory_zip.seek(0)return self.in_memory_zip.read()defwritetofile(self, filename):"""
Write the in-memory zip to a file
"""
f =open(filename,'wb')
f.write(self.read())
f.close()if __name__ =='__main__':
contens ='xxxxxxxxx'# 内存数据
imz = InMemoryZIP()
imz.append('test.txt', contens)
imz.writetofile('test.zip')