[英]python not properly reading in text file
我正在嘗試閱讀看起來像這樣的文本文件:
Date, StartTime, EndTime
6/8/14, 1832, 1903
6/8/14, 1912, 1918
6/9/14, 1703, 1708
6/9/14, 1713, 1750
這就是我所擁有的:
g = open('Observed_closure_info.txt', 'r')
closure_date=[]
closure_starttime=[]
closure_endtime=[]
file_data1 = g.readlines()
for line in file_data1[1:]:
data1=line.split(', ')
closure_date.append(str(data1[0]))
closure_starttime.append(str(data1[1]))
closure_endtime.append(str(data1[2]))
我這樣做是為了一個與此文件非常相似的前一個文件,一切正常。 但是,此文件未正確讀取。 首先它為closure_starttime.append(str(data1[1]))
給出了一個錯誤“list index out of range”,當我要求它打印它對data1或closure_date的內容時,它給了我類似的東西
['\x006\x00/\x008\x00/\x001\x004\x00,\x00 \x001\x008\x003\x002\x00,\x00 \x001\x009\x000\x003\x00\r\x00\n']
我已經嘗試重寫文本文件,以防有關該特定文件有任何損壞,它仍然做同樣的事情。 我不確定為什么,因為上次這個工作正常。
有什么建議? 謝謝!
這看起來像一個逗號分隔的文件,具有UTF-16編碼(因此\\x00
空字節)。 您必須解碼來自UTF-16的輸入,如下所示:
import codecs
closure_date=[]
closure_starttime=[]
closure_endtime=[]
with codecs.open('Observed_closure_info.txt', 'r', 'utf-16-le') as g:
g.next() # skip header line
for line in g:
date, start, end = line.strip().split(', ')
closure_date.append(date)
closure_starttime.append(start)
closure_endtime.append(end)
試試這個
g = open('Observed_closure_info.txt', 'r')
closure_date=[]
closure_starttime=[]
closure_endtime=[]
file_data1 = g.readlines()
for line in file_data1[1:]:
data1=line.decode('utf-16').split(',')
closure_date.append(str(data1[0]))
closure_starttime.append(str(data1[1]))
closure_endtime.append(str(data1[2]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.