简体   繁体   English

TypeError:必须是str,而不是字节Error

[英]TypeError: must be str, not bytes Error

In a python code of mine, I am getting this error while execution of this line. 在我的python代码中,执行此行时出现此错误。

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. 它在python 2.7上运行正常,但在python 2.7下运行正常。

In Python 3, file objects opened in text mode require you to write Unicode text . 在Python 3中,以文本模式打开的文件对象要求您编写Unicode文本

You encoded your text to UTF-8 bytes, but it is the responsibility of the file object to do the encoding. 您已将文本编码为UTF-8字节,但是文件对象有责任进行编码。 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. 通过使用io.open()函数而不是内置的open()函数,可以在Python 2中获得相同的行为。 The io module in Python 2 is a backport of the new I/O infrastructure used in Python 3. Python 2中的io模块是Python 3中使用的新I / O基础结构的反向移植。

If you need to write polyglot code (Python code that works both on Python 2 and Python 3), simply import from io : 如果您需要编写多语言代码(适用于Python 2和Python 3的Python代码),只需从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() . Python 3内置的open()函数与io.open()完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM