解决Python使用open函数读取文件报编码问题

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
posted @ 2020-10-21 16:56  凯尔哥  阅读(2717)  评论(0编辑  收藏  举报