所以我有一个StringIO()类似文件的对象,我正在尝试将其写入a ZipFile(),但是我得到了这个TypeError:
coercing to Unicode: need string or buffer, cStringIO.StringI found
Run Code Online (Sandbox Code Playgroud)
以下是我正在使用的代码示例:
file_like = StringIO()
archive = zipfile.ZipFile(file_like, 'w', zipfile.ZIP_DEFLATED)
# my_file is a StringIO object returned by a remote file storage server.
archive.write(my_file)
Run Code Online (Sandbox Code Playgroud)
文档说这StringIO()是一个类文件类,ZipFile()可以接受类文件对象.有什么我想念的吗?任何帮助将不胜感激.
提前致谢!
我避免在磁盘上创建文件,这是我到目前为止所得到的:
def get_zip(request):
import zipfile, StringIO
i = open('picture.jpg', 'rb').read()
o = StringIO.StringIO()
zf = zipfile.ZipFile(o, mode='w')
zf.writestr('picture.jpg', i)
zf.close()
o.seek(0)
response = HttpResponse(o.read())
o.close()
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename=\"picture.zip\""
return response
Run Code Online (Sandbox Code Playgroud)
你认为是正确的 - 优雅 - pythonic足够吗?有更好的方法吗?
谢谢!