關於python中匯入檔案到list的問題
阿新 • • 發佈:2020-11-02
使用python實現檔案匯入,具體方法如下:
檔案樣例可以自己random
這裡的temp1根據每一行的分隔符來讀入,‘\n'表述回車
temp2表示每一行內的分隔符,可以自定義(例如圖中',',還有'\t'表示空格等)
def loadDatadet(infile): f=open(infile,'r') sourceInLine=f.readlines() dataset=[] for line in sourceInLine: temp1=line.strip('\n') temp2=temp1.split(',') dataset.append(temp2) return dataset infile=r'C:\Users\Clevo\Desktop\infile.txt' infile=loadDatadet(infile) print(infile)
返回一個list資料集dataset
當上面infile路徑中直接寫句對路徑會報錯
(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escap
這裡是因為在Python中\是轉義符,\u表示其後是UNICODE編碼,因此\User在這裡會報錯,在字串前面加個r表示就可以了。
到此這篇關於關於python中匯入檔案到list的問題的文章就介紹到這了,更多相關python匯入檔案到list內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!