【问题标题】:how to create csvs and write to zip file in Google App Engine (python)?如何在 Google App Engine (python) 中创建 csvs 并写入 zip 文件?
【发布时间】:2014-04-19 05:41:49
【问题描述】:

我正在尝试将多个 csv 写入 Google App Engine 中的 zip 文件。我找到了这篇文章:Confused about making a CSV file into a ZIP file in django,这很有帮助。事实上,当我这样做时:

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

我得到一个空白的 zip 文件,这很好。但是,在此之上,我有

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'])

这本身就可以让我下载 csv。当我尝试将两者结合起来时,我遇到了困难。如果我这样做:

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

我得到一个无法打开的 zip 文件。我相当确定我使用 writestr 不正确,但我无法弄清楚将我创建的 csv 放入 zip 的代码。有人可以帮忙吗?

【问题讨论】:

  • 您是说您正在将 两个 文件写入响应吗? CSV zipfile?
  • 这里的output是什么(来自output.getvalue(),写入ZipFile()对象)?
  • 嗯我猜 writer = csv.writer(self.response.out) 应该有不同的论点,对吗?我只想将一个文件写入响应(压缩文件)
  • 我不确定如何创建 csv 并将其“保存”在内存中以将其添加到 zip 文件中。

标签: python google-app-engine csv zip zipfile


【解决方案1】:

这就是我正在做的事情

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

【讨论】:

  • 有道理;那么payload会是什么返回的(即self.response.out.write(payload))?
猜你喜欢
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-27
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多