python中的csv模块的bug

时间:2015-07-20 23:13:19

标签: python python-2.7 csv

import csv
with open('database.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['NAME'])

伙计们,我有一个csv文件,第一行作为索引,在linux中,代码从行[' NAME']中读取,只打印名称形成colum NAME,当我运行它时窗户,它说:

C:\Users\Desktop>python py.py
Traceback (most recent call last):
  File "py.py", line 5, in <module>
    print(row['NAME'])
KeyError: 'NAME'

为什么?

1 个答案:

答案 0 :(得分:3)

如果您使用的是python 2-版本,则需要使用rb打开csv,即:

with open('database.csv', 'rb') as csvfile:....

供参考,结帐https://docs.python.org/2/library/csv.html因为它包含了读者文档中有关此内容的一部分。