python识别文件格式的方法-创新互联
创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

小编给大家分享一下python识别文件格式的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨方法吧!
话不多说,直接上代码:
"""
自动识别 文本编码格式
"""
import chardet
def detectCode(path):
with open(path, 'rb') as file:
data = file.read(20000)
dicts = chardet.detect(data)
return dicts["encoding"]
def print_data_1(path):
"""
这种编码通过命令行 file -i 文件名获取编码格式,
通过测试,使用file 命令获取的编码格式不能获取正确的编码数据
:param path:
:return:
"""
with open(path, "r", encoding="iso-8859-1") as f:
i = 0
for line in f:
print(line)
i += 1
if i == 5:
break
f.close()
def print_data_2(path):
print("-------------------------------")
with open(path, "r", encoding="{0}".format(detectCode(path))) as f:
i = 0
for line in f:
b_line = line.encode("utf-8") # 将文件内容转化为utf-8格式
print(chardet.detect(b_line)['encoding']) # 输出转化为内容格式
i += 1
if i == 5:
break
f.close()
if __name__ == '__main__':
path = "test.txt"
print(detectCode(path))
# print_data_1(path)
print_data_2(path)看完了这篇文章,相信你对python识别文件格式的方法有了一定的了解,想了解更多相关知识,欢迎关注创新互联-成都网站建设公司行业资讯频道,感谢各位的阅读!
本文标题:python识别文件格式的方法-创新互联
URL标题:http://www.jxjierui.cn/article/dhhics.html


咨询
建站咨询
