Harshit
Harshit

Reputation: 5157

TypeError: must be str, not bytes Error

In a python code of mine, I am getting this error while execution of this line.

fo.write(text.replace("'","").encode("utf8"));

Error :

TypeError: must be str, not bytes

It was working fine with python 2.7 but with 3, it is giving error.

Upvotes: 2

Views: 8653

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

In Python 3, file objects opened in text mode require you to write Unicode text.

You encoded your text to UTF-8 bytes, but it is the responsibility of the file object to do the encoding. Don't encode the text.

You can get the same behaviour in Python 2, by using the io.open() function rather than the built-in open() function. The io module in Python 2 is a backport of the new I/O infrastructure used in Python 3.

If you need to write polyglot code (Python code that works both on Python 2 and Python 3), simply import from io:

import io

with io.open(filename, 'w', encoding='utf8') as fo:
    fo.write(text.replace("'",""))

The Python 3 built-in open() function is the exact same function as io.open().

Upvotes: 6

Related Questions