Adding word document object variable inside a zip folder object

Hello,

I create word documents on the fly and I would like to add them in a zip folder object (zipObj = ZipFile(‘Sample.zip’, ‘w’)) that will be downloadable in a web page.
How do you add a word document object variable into a zip folder object in python (Note that the word document is not a word document that is already saved in my desktop but a document variable that come from the ‘docx’ module)?

Thank you for your help.

Are you looking for the writestr method on the ZipFile object?

Hello Ken,

I did not use this method but the write method combine with an io.bytesIO stream to add word file( with their format) to a ZIP archive object:

f = io.BytesIO()
zipObj = ZipFile(f, ‘a’)
for File_name in Obj_Attr_List:
Contrat_word = Create_Word_Contract(File_name)
Contrat_word.save(File_name + ‘.docx’)
zipObj.write(File_name + ‘.docx’)
zipObj.close()
response = HttpResponse(f.getvalue(),content_type=‘application/zip’)
response[‘Content-Disposition’] = ‘attachment; filename=ZipArchName.zip’
return response

Thanks again for your help!
PJ