python通过第三方库chardet以字节的形式读入字节流对象,然后通过detect函数识别文件的格式。
""" 自动识别文本编码格式 """ importchardet defdetectCode(path): withopen(path,'rb')asfile: data=file.read(20000) dicts=chardet.detect(data) returndicts["encoding"] defprint_data_1(path): """ 该编码通过命令行file-i文件名获取编码格式, 通过测试,使用file命令获得的编码格式无法获得正确的编码数据 :parampath: :return: """ withopen(path,"r",encoding="iso-8859-1")asf: i=0 forlineinf: print(line) i+=1 ifi==5: break f.close() defprint_data_2(path): print("-------------------------------") withopen(path,"r",encoding="{0}".format(detectCode(path)))asf: i=0 forlineinf: b_line=line.encode("utf-8")#将文件内容转换为utf-8格式 print(chardet.detect(b_line)['encoding'])#输出转换为内容格式 i+=1 ifi==5: break f.close() if__name__='__main__': path="test.txt" print(detectCode(path)) #print_data_1(path) print_data_2(path)
推荐课程:Python高级视频教程