自學(xué)Python一周,嘗試用Python讀取自己編寫的txt文件,文件讀取時總遇到些小問題,以下是個人的總結(jié)
Python的文件分兩種:文本文件及二進制文件。
文本文件:以純ASCII編碼
二進制文件:音頻,視頻,圖像文件等。
文件的讀取包括:文件打開,文件操作,文件關(guān)閉等
文件的打開模式,讀取模式有以下幾種:


以下是一段簡單的文件讀取代碼:
import codecs#庫導(dǎo)入,方便文件讀取,解碼
def getData(lst):
? ? ? #解碼,data.txt編碼格式為utf-8
? ? ?#編寫txt時要注意編碼格式的選擇,有utf-8 without BOM 及utf-8格式,相應(yīng)的解碼格式為‘utf-8’,'utf-8-sig'
? ? ?with codecs.open('data.txt','r','utf-8-sig') as infile:
? ? ? ? ? ? line = infile.readline()
? ? ? ? ? ? ?while line!='':
? ? ? ? ? ? ? ? ? ? ? line = line.strip()#去除前后空格
? ? ? ? ? ? ? ? ? ? ? ?lines = list(map(float,line.split(',')))#分割字符串,并轉(zhuǎn)為list累型
? ? ? ? ? ? ? ? ? ? ? ?lst.append(lines)
? ? ? ? ? ? ? ? ? ? ? ?line = str(infile.readline())
? ? ? ? ? ? ? ? print(lst)
? ? ? ? infile.close()
#函數(shù)調(diào)用
getData()
data.txt
300,0,144,1,0,0
300,0,144,0,1,0
300,0,144,0,0,1
300,0,144,1,1,0
300,0,108,0,1,1
184,0, 72,1,0,1
184,0, 72,0,0,0
184,0, 72,0,0,0
184,0, 72,0,0,0
文件讀取問題:
1. ?lines = list(map(float,line.split(',')))
ValueError: could not convert string to float: '\ufeff300'
解碼格式不對應(yīng)導(dǎo)致出錯,參考編碼與解碼:
stackoverflow.com/questions/17912307/u-ufeff-in-python-string
2.編寫txt文件時要注意編碼格式的選擇,文件讀取時要進行相應(yīng)的解碼
3.ANSI編碼格式時,無需解碼