python – 为什么csv.DictReader给我一个no属性错误?

我的CSV文件是

200
Service

我在解释器中输入的代码是

snav = csv.DictReader(open("screennavigation.csv"), delimiter=',')
print snav.fieldnames
['200']

for line in snav:
...     print(line)
...
{'200': 'Service'}

snav["200"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: DictReader instance has no attribute '__getitem__'

我以为DictReader是为了返回字典.我怀疑我错过了一些非常明显的东西.

最佳答案 snav对象是DictReader实例,不应该作为字典访问.在迭代时,它会生成可以相应访问的字典:你需要行[‘200’]

点赞