无法多次迭代csv DictReader

时间:2015-03-21 17:52:59

标签: python list python-2.7 csv

在Python(2.7.6)中,我试图从CSV文件的某些列中获取列表。给定CSV文件test.csv,其内容为:

COL_ONE,COL_TWO,COL_THREE
val_R1C1,val_R1C2,val_R1C3
val_R2C1,val_R2C2,val_R2C3
val_R3C1,val_R3C2,val_R3C3
val_R4C1,val_R4C2,val_R4C3

我希望以下代码能为我做到这一点:

import csv

reader = csv.DictReader(open("test.csv", "r"))
col2 = list(c2['COL_TWO'] for c2 in reader)
col3 = list(c3['COL_THREE'] for c3 in reader)

不幸的是,当我打印两个列表col2和col3时,第二个列表为空。

['val_R1C2', 'val_R2C2', 'val_R3C2', 'val_R4C2']
[]

此替代方案具有相同的结果:

reader = csv.DictReader(open("test.csv", "r"))
col2 = []
for c2 in reader:
    col2.append(c2['COL_TWO'])
col3 = []
for c3 in reader:
    col3.append(c3['COL_THREE'])

解决方法很简单:

col2 = []
col3 = []
for cval in reader:
    col2.append(cval['COL_TWO'])
    col3.append(cval['COL_THREE'])

我得到了前两个例子中的预期:

['val_R1C2', 'val_R2C2', 'val_R3C2', 'val_R4C2']
['val_R1C3', 'val_R2C3', 'val_R3C3', 'val_R4C3']

我很感激一些帮助,以了解我做错了什么。为什么我在这三种情况下得不到相同的结果?

1 个答案:

答案 0 :(得分:0)

将基础文件倒回到读取之间的0位置:

import csv

fh = open("test.csv", "r")
reader = csv.DictReader(fh)
next(reader) # skip header row
col2 = list(c2['COL_TWO'] for c2 in reader)
fh.seek(0)  ## <------------------- this is the point
next(reader) # skip header row
col3 = list(c3['COL_THREE'] for c3 in reader)