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

import chardet #导入chardet库
'''
1.推荐地址: http://download.csdn.net/download/aqwd2008/4256178 
2.官方地址: http://pypi.python.org/pypi/chardet
如果采用源代码安装方法,有可能会提示缺少setuptools这个模块。
因此这里我们采用另外一种更为方便的安装方法,不论你选择哪种安装包,
将它解压得到其中的文件夹【chardet】将这个文件夹复制到
【python安装根目录\Lib\site-packages】下,确保这个位置可以被python引用到。
如果不能被引用到请加入环境变量。
'''   

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')
'''
博客来自:
https://blog.csdn.net/Ltinginger/article/details/83105266
'''

  

posted @ 2019-07-17 14:12  一克拉小猎  阅读(4227)  评论(0编辑  收藏  举报