我该如何将Python的StringIO()对象传递给ZipFile(),或者这种操作不被支持?

11

我有一个类似于文件的对象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()可以接受类似文件的对象。我是否漏掉了什么?


3
ZipFile.write()的参数是一个文件名。 - Sven Marnach
1
刚刚发现这个问题;你的第二行有一个拼写错误吗?还是那是你实际的代码?ZipFile(file_file而不是ZipFile(file_like - Bogdacutu
1个回答

14

要向ZipFile添加一个字符串,需要使用writestr方法,并通过StringIO实例的getvalue方法传递来自StringIO的字符串。

例如:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接