Python 3:使用内存 Xml 创建内存 Zipfile

Posted

技术标签:

【中文标题】Python 3:使用内存 Xml 创建内存 Zipfile【英文标题】:Python 3: create in-memory Zipfile with in-memory Xml 【发布时间】:2020-09-14 08:22:45 【问题描述】:

我正在尝试使用 io.StringIO() 创建 xml 文件并将其打包到 ZipFile 中,但输出是一个空的 zip 文件。哪里出错了?

string_xml_buffer = io.StringIO()
string_xml_buffer.write('<MyContent>')
string_xml_buffer.write('</MyContent>')
bytes_zip_buffer = io.BytesIO()
zf = ZipFile(bytes_zip_buffer, mode = 'w')
zf.writestr('filename.xml', string_xml_buffer.getvalue())

# Django response
response = HttpResponse(zf, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="f.zip"'
return response

【问题讨论】:

【参考方案1】:

问题在于缺少zf.close()。使用这一行代码效果很好。

【讨论】:

以上是关于Python 3:使用内存 Xml 创建内存 Zipfile的主要内容,如果未能解决你的问题,请参考以下文章