python编程:合并文本为什么出现gbk' codec can't decode byte 0xb2 in position 87: illegal multibyte sequence

img

img


为什么运行之后出错
显示 'gbk' codec can't decode byte 0xb2 in position 87: illegal multibyte sequence

在一、二行打开文本的语句中,添加编码参数:encoding='utf-8'。

1.在打开文本时候,可以指明打开方式:

file = open(path, encoding='gbk')

2.如果上一步还不能解决,可能是文本中出现的一些特殊符号超出了gbk的编码范围,可以选择编码范围更广的‘gb18030’,如:

 file = open(path, encoding='gb18030'

3.如果上一步还不能解决,说明文中出现了连‘gb18030’也无法编码的字符,可以使用‘ignore’属性忽略非法字符,如:

file = open(path, encoding='gb18030', errors='ignore')

或者

file=open(path).read().decode(‘gb18030’,’ignore’)