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

后端 未结 1 1082
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 14:47

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

coercing to Unicode: need string or buffer, c         


        
相关标签:
1条回答
  • 2021-01-11 15:12

    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.

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

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

    0 讨论(0)
提交回复
热议问题