python识别文件格式的方法
小编给大家分享一下python识别文件格式的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨方法吧!
话不多说,直接上代码:
"""自动识别文本编码格式"""importchardetdefdetectCode(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=0forlineinf:print(line)i+=1ifi==5:breakf.close()defprint_data_2(path):print("-------------------------------")withopen(path,"r",encoding="{0}".format(detectCode(path)))asf:i=0forlineinf:b_line=line.encode("utf-8")#将文件内容转化为utf-8格式print(chardet.detect(b_line)['encoding'])#输出转化为内容格式i+=1ifi==5:breakf.close()if__name__=='__main__':path="test.txt"print(detectCode(path))#print_data_1(path)print_data_2(path)
看完了这篇文章,相信你对python识别文件格式的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。