无法遍历两个csv文件并进行比较

时间:2019-11-12 15:17:02

标签: python-2.7 csv

我是python(2.7)的新手,需要帮助遍历2个CSV文件。如果第二个文件(内循环)满足某些条件,则第一个文件(外循环)是我要写入的行。

import csv

f = open('../CI Working Copy.csv')
with open('../first.csv', 'wb') as n:
    theWriter = csv.writer(n)
    csv_f = csv.reader(f)
    g = open('../second.csv')
    csv_g = csv.reader(g)
    for row in csv_f:
        cbd = row[3]
        ced = row[4]
        rbd = row[5]
        red = row[6]
        ciCn = row[10]
        for iRow in csv_g:
            cn = iRow[0]
            startDate = iRow[1]
            endDate = iRow[2]
            iId = iRow[3]
            writeRow = 'false'
            if ciCn == cn:
                if (cbd == startDate and ced == endDate) or (rbd == startDate and red == endDate):
                    theWriter.writerow(row)
    g.close()
f.close()

它进入第二个(内循环)文件,但从不返回外循环。我只需要从第一个文件写入行。

1 个答案:

答案 0 :(得分:1)

对于第一个csv文件的每一行,您将消耗所有第二个文件,因此在每次迭代时都需要返回第二个文件的开头。

解决方案是:

for row in csv_f:
        g.seek(0) #go at the start of the second file
        for iRow in csv_g:
            do_smth(iRow,row)
g.close()