从csv打印第一列时,Python'KeyError:0'

时间:2015-12-14 11:32:27

标签: python csv

我是python中的新手,并尝试按列索引读取每一行,但在执行下面的代码时获取KeyError: 0

with open('processed/test.csv') as f:
    reader = csv.DictReader(f) 
    for row in reader:
        print row[0]

是否有人知道如何按索引读取列?

1 个答案:

答案 0 :(得分:3)

你的行是空的。下一步:


with open('processed/test.csv') as f:
    reader = csv.DictReader(f) 
    for row in reader:
        if len(row):
            print row

为什么你要使用DictReader,如果你想逐个索引?可能是,你的代码应该是这样的吗?


with open('processed/test.csv') as f:
    reader = csv.reader(f) 
    for row in reader:
        print ', '.join(row)
        if len(row):
            print row[0]