【问题标题】:How can I pass a Python StringIO() object to a ZipFile(), or is it not supported?如何将 Python StringIO() 对象传递给 ZipFile(),或者它不受支持?
【发布时间】:2011-09-12 02:03:20
【问题描述】:

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

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.write() 的参数是文件名。
  • 刚找到这个;您的第二行是否有错字,还是您的实际代码? ZipFile(file_file 而不是 ZipFile(file_like

标签: python zipfile stringio


【解决方案1】:

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

例如

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

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

【讨论】:

    猜你喜欢
    • 2015-05-15
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多