0

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

0

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank, I tried to add csv2.seek(0) but I got the error message, AttributeError: '_csv.reader' object has no attribute 'seek' and then the another answer came and worked. Thanks for your time.
No problem, my answer explains the reason for the problem that you had, and the other answer is probably a better solution. Note that csv2 is a file object. It looks like you might have tried read2.seek(0) instead of csv2.seek(0)?
Yep maybe I did =S, sorry about that! That s embarrassing. Cheers in any case.
0

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])

1 Comment

No worries, you're welcome. If the file was very large you could use seek but for a thousand elements you will be fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.