import chardet import string path1= r'C:Users25456Desktop' path = path1 + r'深度学习.txt' with open(path, 'rb') as f: data = f.read() f_charInfo=chardet.detect(data) print (f_charInfo) 输出:{'encoding': 'GB2312', 'language': 'Chinese', 'confidence': 0.99}
其中:encoding表示编码,confidence表示置信度,即判断文件0.99的可能性为GB2312编码
然后就可以正常读取文件,不会出现乱码了:
with open(path, 'rb') as f: result = f.read() result = result.decode(encoding='GB2312') print (result)