Python读取txt文件报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0

  Python使用open读取txt中文内容的文件时,有可能会报错,报错内容如下:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0。

  这里举一个例子:txt=open("threekingdoms.txt","r",encoding="utf-8").read(),在运行时就会报错。

  要处理这个问题有两个办法,如下:

    第一个办法,将编码方式由utf-8改为gb18030,即txt=open("threekingdoms.txt","r",encoding="gb18030").read()。

    第二个办法,将原来的txt文件另存为,在保存时将编码由ANSI改为UTF-8。

参考:https://blog.csdn.net/xxceciline/article/details/80405129

原文地址:https://www.cnblogs.com/diantong/p/12613204.html