如何将Python StringIO()对象传递给ZipFile(),或者不支持该对象? [英] How can I pass a Python StringIO() object to a ZipFile(), or is it not supported?

查看:477
本文介绍了如何将Python StringIO()对象传递给ZipFile(),或者不支持该对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 StringIO() 类似于文件的对象,并且我尝试将其写入 ZipFile() ,但我收到此TypeError:

So I have a StringIO() file-like object, and I am trying to write it to a ZipFile(), but I get this TypeError:

coercing to Unicode: need string or buffer, cStringIO.StringI found

以下是我正在使用的代码示例:

Here is a sample of the code I am using:

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)

文档说 StringIO() 是文件-类似于类,并且 ZipFile() 可以接受类似文件的对象.有什么我想念的吗?任何帮助将不胜感激.

The docs say that StringIO() is a file-like class and that ZipFile() can accept a file-like object. Is there something I am missing? Any help would be greatly appreciated.

提前谢谢!

推荐答案

要将字符串添加到ZipFile,您需要使用writestr方法,并使用StringIO实例的getvalue方法从StringIO传递字符串

To add a string to a ZipFile you need to use the writestr method and pass the string from StringIO using getvalue method of the StringIO instance

例如

archive.writestr("name of file in zip", my_file.getvalue())

请注意,您还需要提供字符串名称,以说明该字符串在zip文件中的放置位置.

Note you also need to give the name of the string to say where it is placed in the zip file.

这篇关于如何将Python StringIO()对象传递给ZipFile(),或者不支持该对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆