Frage

I'm trying to write multiple csvs to a zip file in Google App Engine. I found this post: Confused about making a CSV file into a ZIP file in django which has been helpful. In fact, when I do:

o=StringIO.StringIO()
file = zipfile.ZipFile(file=o,compression=zipfile.ZIP_DEFLATED,mode="w")
.. . ## add your csv files here
file.close()
o.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="your_csvs.zip"'
self.response.out.write(o.getvalue())

I get a blank zip file which is fine. However, above this, I have

self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=sheet.csv'
writer = csv.writer(self.response.out)
writer.writerow(['Text Here'])

Which by itself lets me download a csv. Where I'm stuck is when I try to combine the two. If I do:

self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=sheet.csv'
writer = csv.writer(self.response.out)
writer.writerow(['Text Here'])

o=StringIO.StringIO()
file = zipfile.ZipFile(file=o,compression=zipfile.ZIP_DEFLATED,mode="w")
file.writestr("sheet.csv", output.getvalue())
file.close()
o.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="your_csvs.zip"'
self.response.out.write(o.getvalue())

I get a zipfile that can't open. I'm fairly certain I'm using writestr incorrectly but I can't figure out the code to get the csv I create into the zip. Can anyone help?

War es hilfreich?

Lösung

Here is what I am doing

        zh = StringIO()
        zf = zipfile.ZipFile(zh,'w')
        zi = zipfile.ZipInfo('test.csv')
        zi.compress_type = zipfile.ZIP_DEFLATED
        zi.comment = 'Some comment'
        zf.writestr(zi, zh.getvalue())
        zf.close()
        payload = zh.getvalue()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top