如何将Python StringIO()对象传递给ZipFile(),或者不支持该对象?


问题内容

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

提前致谢!


问题答案:

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

例如

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

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