如何将Python StringIO()对象传递给Zip文件(),还是不受支持?

时间:2011-06-09 21:47:51

标签: python zipfile stringio

所以我有一个StringIO()类似文件的对象,我正在尝试将它写入ZipFile(),但是我得到了这个TypeError:

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

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

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()可以接受类似文件的对象。有什么我想念的吗?任何帮助将不胜感激。

提前致谢!

1 个答案:

答案 0 :(得分:14)

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

e.g。

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

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