Bootstrap

Bug:UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xa3 in position

Traceback (most recent call last):
File "D:\PyCharm Community Edition 2022.3\_CODE\Project_GIINI\main.py", line 18, in <module>
for row in csv_reader:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa3 in position 22: illegal multibyte sequence

解决方法

读取文件时报错Unicode编码错误,一般这种情况较多是在国标码(GBK)和utf8之间选择出现了问题。

这个异常报错是由于设置了参数errors默认为严格(strict)造成的,将其更改为ignore等即可。

添加:, encoding='gbk', errors='ignore'


报错

# 获得文件行数countLine
countLine = 0
with open(fileName, 'r') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        countLine += 1
print('The total number of rows of data:', countLine)

'''
Traceback (most recent call last):
  File "D:\PyCharm Community Edition 2022.3\_CODE\Project_GIINI\main.py", line 18, in <module>
    for row in csv_reader:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa3 in position 22: illegal multibyte sequence
'''

解决

# 获得文件行数countLine
countLine = 0
with open(fileName, 'r', encoding='gbk', errors='ignore') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        countLine += 1
print('The total number of rows of data:', countLine)

;