[英]How to resolve KeyError: <variable> in Python?
Hi I'm trying to open simple csv file with the header from an external file: 嗨,我正在尝试使用外部文件的标题打开简单的csv文件:
got next file named: name.csv with next content: 得到了下一个名为: name.csv的文件, 其中包含下一个内容:
Leo,Days,Ju
Tomas,Lee,Bruce
Max,Perez,Smith
If I code: 如果我编码:
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))
The result is desired like: 结果是所希望的,例如:
Leo,Ju
Tomas,Bruce
Max,Smith
But if got an extra file with headers named hdr_name.txt with: 但是,如果有一个额外的文件,其标题为hdr_name.txt ,其标题为:
['name', 'paterno', 'materno']
With this new code: 有了这个新代码:
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))
Got as result: 结果是:
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
KeyError: 'name'
But if I ask for 'name' in fieldnames, is there! 但是,如果我在字段名称中要求输入“名称”,那么就在那里!
>>> 'name' in fieldnames
True
>>>
What I'm doing wrong, with opening header from external file ? 从外部文件打开标头,我在做什么错?
fieldnames
is a string that looks like this: fieldnames
是一个看起来像这样的字符串:
"['name', 'paterno', 'materno']"
Naturally, a membership test will return true, but that does not imply fieldnames
is a list. 自然,成员资格测试将返回true,但这并不意味着
fieldnames
是一个列表。 Remember, file.read
returns a string - you still need to cast it to a list. 请记住,
file.read
返回一个字符串-您仍然需要将其file.read
转换为列表。
This doesn't appear to look like JSON, so I'd recommend ast
: 这看起来似乎不像JSON,所以我建议
ast
:
import ast
with open('hdr_name.txt', 'r') as f:
fieldnames = ast.literal_eval(f.read().strip())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.