Python: Why am I getting a UnicodeDecodeError?

雨燕双飞 提交于 2019-12-06 15:55:55

In python 3, when you open a file for reading in text mode (r) it'll decode the contained text to unicode.

Since you didn't specify what encoding to use to read the file, the platform default (from locale.getpreferredencoding) is being used, and that fails in this case.

You need to either specify an encoding that can decode the file contents, or open the file in binary mode instead (and use b'' bytes patterns for your regular expressions).

See the Python Unicode HOWTO for more information.

I'm not too familiar with python 3x, but the below may work.

inputFile = open((x, encoding="utf8"), "r")
ash kim

There's a similar question here: Python: Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0]

But you might want to try:

 open((x), "r", encoding='UTF8')
sjlouis

Thank you very much for this solution. It helps me for another subject, I used :

exec (open ("DIP6.py").read ())

and I got this error because I have this symbol in a comment of DIP6.py :

 #       ● en première colonne

It works fine with :

exec (open ("DIP6.py", encoding="utf8").read ())

It also solves a problem with :

print("été") for example

in DIP6.py

I got :

été

in the console.

Thank you :-) .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!