新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么識(shí)別文件格式
python通過(guò)第三方庫(kù)chardet以字節(jié)方式讀進(jìn)字節(jié)流對(duì)象,然后通過(guò)detect函數(shù)識(shí)別進(jìn)而獲取文件的格式。
創(chuàng)新互聯(lián)于2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目做網(wǎng)站、網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元瀘溪做網(wǎng)站,已為上家服務(wù),為瀘溪各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
"""
自動(dòng)識(shí)別 文本編碼格式
"""
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):
"""
這種編碼通過(guò)命令行 file -i 文件名獲取編碼格式,
通過(guò)測(cè)試,使用file 命令獲取的編碼格式不能獲取正確的編碼數(shù)據(jù)
: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") # 將文件內(nèi)容轉(zhuǎn)化為utf-8格式
print(chardet.detect(b_line)['encoding']) # 輸出轉(zhuǎn)化為內(nèi)容格式
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進(jìn)階視頻教程
當(dāng)前文章:創(chuàng)新互聯(lián)Python教程:python怎么識(shí)別文件格式
網(wǎng)頁(yè)網(wǎng)址:http://m.5511xx.com/article/cooidch.html


咨詢
建站咨詢

