问题描述
报错UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 0: unexpected end of data
data = b"\xad\xa3\xe5\x9b\x9b\xe5\xb7\x9d"
try:
print(data.decode('utf-8')) # 会报错,多了\xad\xa3
except Exception as e:
print(e) # 'utf-8' codec can't decode byte 0xad in position 0: invalid start byte
print(data.decode('utf-8', 'ignore')) # 四川
print('四川'.encode('utf-8')) # b'\xe5\x9b\x9b\xe5\xb7\x9d'
解决方案
调用bytes.decode()
时添加参数errors='ignore'
f.read(read_bytes).decode('utf-8', 'ignore')