Python读取文件时出现UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x80 in position ...

with open(self.path, 'r') as test:
     for line in test:
         pass

代码如上,出现错误:UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position ...
 

UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 9: ...

或者是

UnicodeDecodeError: 'gbk' codec can't decode byte 0xb3 in position 9: illegal multibyte sequence

解决方法

主要原因是因为编码的问题,可能是因为0x80这个字节在gbk编码中没有这个字符,可能原字符是两个字节,在gbk里被解析成了一个字节,导致字符不存在。解决方法有两个,一个是二进制读取,一个是改编编码方式:

方法一:二进制读取

 with open(self.path, 'rb') as test:
     for line in test:
         pass

但是这样在读取的是中文文本的时候还可能会产生其他的错误:

TypeError: a bytes-like object is required, not 'str'

方法二:改变打开文件的编码方式

 with open(self.path, 'r', encoding='utf-8') as test:
     for line in test:
         pass

或者

 with open(self.path, 'r', encoding='utf-8-sig') as test:
     for line in test:
         pass

这个utf-8-sig亲测好用,屡试不爽,非常nice

你可能感兴趣的:(各种error总结,python,乱码)