-1

I have 2 CSV files i'm trying to compare "Email" column for match, the below code is fine for comparing but when it iterate through the lines in the file it will print "No Match" after checking every line, I need it to only print "No Match" only after it checks all rows and didn't find match then print "No Match" in the file

could you please help a beginner with that?

with open("new.csv", "r") as csv_file1: 
    csv_reader = csv.DictReader(csv_file1, delimiter=",", quotechar='"')
    for file1Line in csv_reader:

        with open("old.csv", "r") as csv_file2: 
            csv_reader = csv.DictReader(csv_file2, delimiter=",", quotechar='"')
            for file2Line in csv_reader:
                if (
                    file1Line["User ID/Email (Required)"]
                    == file2Line["User ID/Email (Required)"]
                ):
                    print("Match found:")
                else:
                    print("no match")
Hussein
  • 3
  • 1
  • 1
    It prints "no match" every time because you ask it to do that: for every `file2line` in `csv_reader`, `print "Match found"` if some condition is fulfilled. If it is not fulfilled, `print "no match"` Check out `for...else` loops. [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Pranav Hosangadi Apr 16 '21 at 19:42
  • You have an indentation problem in the example. You want your `else:` clause unindented one position so it lines up with the `for` and not the `if`. – RufusVS Apr 16 '21 at 20:08

1 Answers1

0
with open("new.csv", "r") as csv_file1: 
    csv_reader = csv.DictReader(csv_file1, delimiter=",", quotechar='"')
    found = False
    for file1Line in csv_reader:

        with open("old.csv", "r") as csv_file2: 
            csv_reader = csv.DictReader(csv_file2, delimiter=",", quotechar='"')
            for file2Line in csv_reader:
                if (file1Line["User ID/Email (Required)"] 
                == file2Line["User ID/Email (Required)"]):
                    found = True
    
    print ("Match found:" if found else "no match")