python - 如何将 Python StringIO() 对象传递给 ZipFile(),或者它是否不受支持?

标签 python stringio python-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 文件中的位置。

关于python - 如何将 Python StringIO() 对象传递给 ZipFile(),或者它是否不受支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6299724/

相关文章:

python - 一次运行 sed 获取参数子集

python - 我可以像 StringIO 一样使用 cStringIO 吗?

python - 在python中压缩文件

python - 在 Python 中解压缩文件

python - 弹出窗口中的 Kivy 按钮不调用函数

python - 如何使用 for 循环获取用户输入来计算最大值、最小值、平均值?

xml - 字符串 IO 到 element.etree

python - 包含带有多个 csv 文件的 zip 文件的 Django 响应

python - 尝试设置 urls.py 定向到index.html