python读取txt时先自动检测编码方式

python读取txt文档时,经常会编码方式错误,所以这里搜索资源找到一个自动检测文档编码方式的代码,如下:

import chardet
try:
    file1 = open('test.txt','rb')
#打开文件,不要填写encoding信息
    r = file1.read()
    f_charinfo = chardet.detect(r)
    print(f_charinfo) #打印看下chardet.detect(r)是个什么样的字典
    #print(r.decode(f_charinfo['encoding'])) #根据文档编码,灵活打开
    file1.close()
except:
    if file1:
    file1.close()
    print('err')

致谢:
Python读取各种格式的txt文档(ANSI、Unicode、Unicode big endian、UTF-8等)

posted @ 2020-02-12 17:37  songbiao  阅读(321)  评论(0)    收藏  举报