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

11 投票
1 回答
8943 浏览
提问于 2025-04-16 19:17

我有一个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 个回答

13

要把一个字符串添加到一个压缩文件(ZipFile)里,你需要用到一个叫做writestr的方法,并且要通过StringIO的getvalue方法来获取这个字符串。

比如:

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

注意,你还需要给这个字符串起个名字,以便告诉压缩文件它放在什么地方。

撰写回答