python 读取txt文件出现编码问题:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xba in position 5: invalid start byte 或者 UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa7 in position 11144: illegal multibyte sequence等
使用代码:
txt = open('红楼梦.txt','r',encoding = 'utf-8').read()
出现错误:
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xba in position 5: invalid start byte
将代码改成:
txt = open('红楼梦.txt','r',encoding = 'gbk').read()
再次报错:
UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa7 in position 11144: illegal multibyte sequence
这类错误是txt文件编码问题。
解决方案:打开对应txt文件,找到其右下角对应编码方式,如下图
将其输入至代码"encoding ="后面 替换即可,我这里是ANSI。
最后代码更正如下
txt = open('红楼梦.txt','r',encoding = 'ANSI').read()
修改后没有再出现这类报错。
原文链接:https://blog.csdn.net/qq_42518033/article/details/105263182