嗨,我試圖打開簡單的csv文件與外部文件的標題:如何在Python中解決KeyError:<variable>?
了命名一個文件:name.csv與下一個內容:
Leo,Days,Ju
Tomas,Lee,Bruce
Max,Perez,Smith
如果我的代碼:
import csv
sep = ','
with open('name.csv') as csvfile:
fieldnames = ['name', 'paterno', 'materno']
reader = csv.DictReader(csvfile,fieldnames)
for row in reader:
list = (row['name'], \
row['materno'])
print (sep.join(list))
結果所需的像:
Leo,Ju
Tomas,Bruce
Max,Smith
但如果得到了與頭一個額外的文件名爲hdr_name.txt有:
['name', 'paterno', 'materno']
有了這個新代碼:
import csv
sep = ','
fieldnames = open('hdr_name.txt', 'r').read()
with open('name.csv') as csvfile:
print(fieldnames)
reader = csv.DictReader(csvfile,fieldnames)
for row in reader:
list = (row['name'], \
row['materno'])
print (sep.join(list))
得到的結果是:
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
KeyError: 'name'
但如果我在字段名稱中詢問'姓名',在那裏!
>>> 'name' in fieldnames
True
>>>
我做錯了,從外部文件打開標題?
剛剛看了你的頭所以'字段名=開放( 'hdr_name.txt', 'R')readlines方法(。 )' – AndMar
@AndMar不幸的是,它不能修復它,因爲該文件包含帶有str'd列表的單行。 –
是的,這是真的( – AndMar