I have a StringIO()
file-like object, and I am trying to write it to a ZipFile()
, but I get this TypeError:
JavaScript
x
2
1
coercing to Unicode: need string or buffer, cStringIO.StringI found
2
Here is a sample of the code I am using:
JavaScript
1
6
1
file_like = StringIO()
2
archive = zipfile.ZipFile(file_like, 'w', zipfile.ZIP_DEFLATED)
3
4
# my_file is a StringIO object returned by a remote file storage server.
5
archive.write(my_file)
6
The docs say that StringIO()
is a file-like class and that ZipFile()
can accept a file-like object. Is there something I am missing?
Advertisement
Answer
To add a string to a ZipFile you need to use the writestr method and pass the string from StringIO using getvalue method of the StringIO instance
e.g.
JavaScript
1
2
1
archive.writestr("name of file in zip", my_file.getvalue())
2
Note you also need to give the name of the string to say where it is placed in the zip file.