Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python why is my "for entry in csv_compare:" loop iterating only once and getting stuck on the last input

I’m trying to compare 2 csv files and then put the common entries in a 3rd csv to write to file. For some reason it iterates the whole loop for row in csv_input but the entry in csv_compare loop iterates only once and stops on the last entry. I want to compare every row entry with every entry entry.

import csv
finalCSV = {}
with open('input.csv', newline='') as csvfile, open('compare.csv', newline='') as keyCSVFile, open('output.csv', 'w' ,newline='') as OutputCSV:
    csv_input = csv.reader(csvfile)
    csv_compare = csv.reader(keyCSVFile)
    csv_output = csv.writer(OutputCSV)
    csv_output.writerow(next(csv_input))

    for row in csv_input:
        for entry in csv_compare:
            print(row[0] + ' ' + entry[0])
            if row[0] == entry[0]:
                csv_output.writerow(row)
                break
    
print('wait...')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When you break the inner loop and start the next iteration of the outer loop, csv_compare doesn’t reset to the beginning. It picks up where you left off. Once you have exhausted the iterator, that’s it.

You would need to reset the iterator at the top of each iteration of the outer loop, which is most easily done by simply opening the file there.

with open('input.csv', newline='') as csvfile, open('output.csv', 'w' ,newline='') as OutputCSV:
    csv_input = csv.reader(csvfile)
    csv_output = csv.writer(OutputCSV)
    csv_output.writerow(next(csv_input))

    for row in csv_input:
        with  open('compare.csv', newline='') as keyCSVFile:
            csv_compare = csv.reader(keyCSVFile)
            for entry in csv_compare:
                if row[0] == entry[0]:
                    csv_output.writerow(row)
                    break
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading