我有一个 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 文件中的位置。
关于python - 如何将 Python StringIO() 对象传递给 ZipFile(),或者它是否不受支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6299724/