Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 无法迭代两个csv文件并进行比较_Python 2.7_Csv - Fatal编程技术网

Python 2.7 无法迭代两个csv文件并进行比较

Python 2.7 无法迭代两个csv文件并进行比较,python-2.7,csv,Python 2.7,Csv,我对Python2.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

我对Python2.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()

它进入第二个内循环文件,但永远不会返回到外循环。我只需要从第一个文件中写入行

对于第一个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()

你能把你的csv文件的一个样本也放进去吗?它实际上进入了第二个循环。它只是不进入第一个循环的第二次迭代