import chardet #导入chardet库
'''
1.推荐地址: http://download.youkuaiyun.com/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.youkuaiyun.com/Ltinginger/article/details/83105266
'''