python读txt数据报编码错误

读数据代码:

with open(path,'r') as f:
       for line in f:
       line = line.strip()    

报错:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 451428: illegal multibyte sequence

尝试修改代码为:
with open(path,encoding="UTF-8")

又报其他错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 278: invalid start byte

一种最好的办法:

with open(path, 'rb') as f:#使用二进制读取
    for line in f:    #line的数据类型是bytes
        line = str(line)    #将bytes类型转换为str类型
        line = line.strip()

猜你喜欢

转载自www.cnblogs.com/taoyuanming/p/11098914.html
今日推荐