![](/img/trans.png)
[英]Getting KeyError when accessing third column of CSV using DictReader
[英]KeyError when using DictReader()
我有一系列.src文件,我試圖使用DictReader()輸入到字典中。 文件看起來如下(只是標題和第一行):
SRC V2.0.. ........Time Id Event T Conf .Northing ..Easting ...Depth Velocity .NN_Err .EE_Err .DD_Err .NE_Err .ND_Err .ED_Err Ns Nu uSt ....uMag Nt tSt ....tMag .MomMag SeiMoment ...Energy ...Es/Ep .SourceRo AspRadius .StaticSD AppStress DyStressD MaxDispla PeakVelPa PeakAccPa PSt
07-30-2010 07:43:56.543 ND 0 e 0.00 152.54 746.45 1686.31 6000 11.76 11.76 11.76 0.00 0.00 0.00 30 0 num -9.90 30 utm -3.21 -1.12 2.06e+007 2.22e+000 20.93 6.08e+000 0.00e+000 3.83e+004 1.49e+003 0.00e+000 1.52e-005 1.50e-003 0.00e+000 1
無論如何,以下是我的代碼:
import csv
Time = {}
Northing = {}
source_file = open(NNSRC, 'rb')
for line in csv.DictReader(source_file, delimiter = '\t'):
Time = line['........Time'].strip()
Northing = line['.Northing'].strip()
print Time, Northing
它給了我以下錯誤:
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\xy\NNFindStages.py", line 101, in <module>
Time = line['........Time'].strip()
KeyError: '........Time'
如何在不更改文件本身的情況下解決文件頭格式化的奇怪方式?
任何幫助是極大的贊賞!
您的標題行未使用標簽。
當我在沒有制表符的情況下重新創建數據時, csv
模塊返回的行只包含一個( 長 )鍵。 如果我用實際標簽重新創建它,那么我得到:
>>> source_file = open('out.csv', 'rb')
>>> reader = csv.DictReader(source_file, delimiter = '\t')
>>> line = reader.next()
>>> len(line)
37
>>> line.keys()
['Id', '..Easting', '.NE_Err', 'uSt', 'SeiMoment', 'MaxDispla', 'tSt', 'Ns', 'Nt', 'Nu', '.Northing', '.DD_Err', '...Energy', '....uMag', 'V2.0..', 'DyStressD', 'SRC', 'PeakAccPa', '.SourceRo', '........Time', '.EE_Err', 'T', 'Velocity', 'PeakVelPa', 'AspRadius', '...Depth', 'PSt', '....tMag', '.MomMag', 'AppStress', '...Es/Ep', '.ED_Err', 'Event', '.ND_Err', 'Conf', '.StaticSD', '.NN_Err']
>>> line['........Time']
'ND'
>>> line['.Northing']
'746.45'
請注意,這些值不需要剝離; 該模塊為您處理無關的空白。
您可以單獨讀取標題,清理它,然后使用csv
模塊處理其余數據:
source_file = open(NNSRC, 'rb')
header = source_file.readline()
source_file.seek(len(header)) # reset read buffer
headers = [h.strip('.') for h in header.split()]
headers = ['Date'] + headers[2:] # Replace ['SRC', 'V2.0'] with a Date field instead
for line in csv.DictReader(source_file, fieldnames=headers, delimiter = '\t'):
# process line
上面的代碼分別讀取標題行,拆分它並刪除額外的.
您可以通過重置readline緩沖區( .seek()
調用的.seek()
來為更多可行的列鍵創建句點,然后為DictReader
設置文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.