python: TypeError: can't write str to text stream

后端 未结 5 1858
灰色年华
灰色年华 2020-12-15 05:10

I must be doing something obviously wrong here. But what is it, and how do I fix?

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)         


        
5条回答
  •  鱼传尺愫
    2020-12-15 05:28

    The io module differs from the old open in that it will make a big difference between binary and text files. If you open a file in text mode, reading will return Unicode text objects (called unicode in Python 2 and str in Python 3) and writing requires that you give it unicode objects as well.

    If you open in binary mode, you will get 8-bit sequential data back, and that's what you need to write. In Python 2 you use str for this, in Python 3 bytes.

    You are using Python 2, and trying to write str to a file opened in text mode. That won't work. Use Unicode.

提交回复
热议问题