Skip to content
Advertisement

How can I pass a Python StringIO() object to a ZipFile(), or is it not supported?

I have a StringIO() file-like object, and I am trying to write it to a ZipFile(), but I get this TypeError:

JavaScript

Here is a sample of the code I am using:

JavaScript

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

Note you also need to give the name of the string to say where it is placed in the zip file.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement