如题,Python3读取文本时,遇到如下错误:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb0 in position 1813: illegal multibyte sequence
起初以为是编码问题导致,通过修改各种编码问题也未得到解决。。。
file = open("test.txt",encoding='utf-8')
两种解决方案:
file = open("test.txt",errors='ignore')
data = file.readlines()
str_data = data[1][0:5]
print(type(str_data))
print(str_data)
file.close()
测试结果:
<class 'str'>
joint
- 方案2:以二进制读取文件,再将二进制数据转换成想要的类型
file = open("test.txt",'rb')
data = file.readlines()
str_data = data[1][0:5]
str_data1= str(str_data ,'utf-8')
str_data2= str_data.decode('utf-8')
print(type(str_data))
print(type(str_data1))
print(type(str_data2))
print(str_data)
print(str_data1)
print(str_data2)
测试结果:
<class 'bytes'>
<class 'str'>
<class 'str'>
b'joint'
joint
joint
参考链接:
- https://www.jb51.net/article/235285.htm
- https://blog.csdn.net/lqzdreamer/article/details/76549256
- https://blog.csdn.net/qq_31267769/article/details/109128882
|