本文介绍了为什么csv.DictReader给我一个没有属性错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的CSV档案是

  200 
服务
pre>

我输入解释器的代码是

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


... print(line)
...
{'200':'Service'}

snav [200]
回溯(最近最后一次调用):
在< module>中的文件< stdin>,第1行
AttributeError:DictReader实例没有属性'__getitem__'

我认为 DictReader 用于返回字典。我怀疑我遗漏了一些非常明显的东西。

解决方案

snav DictReader 实例,不应作为字典访问。在迭代它产生可以相应地访问的字典:你需要 line ['200']


My CSV file is

200
Service

The code I'm putting into the interpreter is

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__'

I thought that DictReader was meant to return a dictionary. I suspect I'm missing something brutally obvious.

解决方案

snav object is DictReader instance and shouldn't be accessed as a dictionary. On iteration it produces dictionaries that could be accessed accordingly: you need line['200']

这篇关于为什么csv.DictReader给我一个没有属性错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 12:23