python:为什么whis代码只循环一次?

问题描述 投票:0回答:2

我倾向于读取两个csv文件并按键名称打印特定列。首先,我有一个像key = [a,b,c]这样的关键名称列表

我这些代码如下:

with open('./file/report.csv', 'rb') as csvfile,open('./file/all.csv','rb') as csvfile2:
    reader2 = csv.DictReader(csvfile)
    reader3 = csv.DictReader(csvfile2)
    for i in key:
         for row in reader2: 
             for row2 in reader3:
                 if row['Case Id'] == i and row2['name'] == i:
                     a=row['Status']
                     b = row2['result']
                     print a,b

两个csv文件:

report.csv:                         all.csv:        
Case Id       Status                 name           result   
  a             111                   a               1111
  b             222                   b               2222
  c             333                   c               3333

我的预期结果是它将循环三次,因为key列表中有三个元素。预期结果应如下所示:

111 1111
222 2222
333 3333

但实际结果是:

111 1111

它只循环一次。我是新编码的东西,需要一些帮助!谢谢!!

python-2.7 loops
2个回答
1
投票

读者是一次性迭代器,经过一次迭代后耗尽。

这意味着你第二次在reader3没有任何东西,因为你已经耗尽了它。

试试这个:

reader2 = list(csv.DictReader(csvfile)) # optional
reader3 = list(csv.DictReader(csvfile2)) # must

如果您使用的是大文件,请使用更复​​杂的匹配,或者每次只重新打开文件。


0
投票

CVSReader视为文件的一次性迭代器。一旦你读了一行,你就不能回头了,一个读者已经筋疲力尽,你无法在不重新创建的情况下从文件中读取更多数据。一个好的做法是将读者读入内存然后检查它们。例如。:

list2 = list(reader2);
list3 = list(reader3);

for i in key:
     for row in list2: 
         for row2 in list3:
             if row['Case Id'] == i and row2['name'] == i:
                 a=row['Status']
                 b = row2['result']
                 print a,b
© www.soinside.com 2019 - 2024. All rights reserved.