python怎么识别文件格式

Python (173) 2023-06-30 23:08:23

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进阶视频教程

THE END

发表回复