Not Iterating through all lines from a csv file python3

拜拜、爱过 提交于 2020-03-05 15:10:42

问题


I am quite new to python3 and I am sure my question is very basic. I have been looking online for some help and the closest I got came from thread Find Common Region in two CSV File in PYTHON

However in my case it seems it is not iterating through everyline and stop at the first one. SO in my first csv I have 2 lines, lets say:

A,1,A1

B,2,B2

now in my second csv I have a thousand lines, something like

A,1,B5

A,2,A2

B,2,C6

B,3,C7

C,3,D7

C,4,D8

......

my code is as follow:

read1 = csv.reader(csv1) 
for row1 in read1:
    read2 = csv.reader(csv2)
    for row2 in read2:
        if row1[0] == row2[0] and row1[1] == row2[1]:
           print('There is a match', row1[0], row1[1])

However, my output is There is a match A 1 It only finds the first match and not the other matche: B 2 I am not sure what is wrong in my iterations:

Thank you in advance for your help


回答1:


Put the contents in a list :

import  csv
with open(file1) as f1,open(file2) as f2:
    rd1, rd2 = csv.reader(f1) ,list(csv.reader(f2))
    for row1 in rd1:
        for row2 in rd2:
            if row1[0] == row2[0] and row1[1] == row2[1]:
                print('There is a match', row1[0], row1[1])



回答2:


After the first pass of your loops, file csv2 will be at end of file. Subsequent reads will return an empty string. This is true even if you create a new CSV reader using the same file object. For this reason the second match is not found because the second file is effectively not processed.

The easiest solution is to call csv2.seek(0) after processing the second file, i,e:

read1 = csv.reader(csv1) 
for row1 in read1:
    read2 = csv.reader(csv2)
    for row2 in read2:
        if row1[0] == row2[0] and row1[1] == row2[1]:
           print('There is a match', row1[0], row1[1])
    csv2.seek(0)


来源:https://stackoverflow.com/questions/26525723/not-iterating-through-all-lines-from-a-csv-file-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!