1. 先通过open函数指定编码格式,代码如下:

f1= open('/path/name','r', encoding='UTF-8')
# 或者
f1= open('/path/name','r', encoding='GBK')

2. 在使用上述方法都还报错的时候,可以使用如下方法:

def read(file):
    # 先使用二进制的方式读取文件
    with open(file, 'rb') as f:
    res = ''
    for line in f:
        try:
            # 然后一行一行地尝试解码
            res += line.decode("utf-8").strip()
        except:
            pass
        try:
            res += line.decode("gbk").strip()
        except:
            pass
    temp = res.split()
    res = ''.join(temp)
    return res

相关文章:

  • 2021-03-26
  • 2022-01-19
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-22
  • 2022-12-23
  • 2021-07-03
  • 2021-05-28
  • 2022-12-23
  • 2021-11-19
  • 2021-08-02
相关资源
相似解决方案