2

I am trying to compare two csv files and write to a third if they match (The comparison/writing works fine). My issue is with iteration. In the below example, my program will print 1 as many times as there are lines in s. If i move the print up a level and remove the for loop for s, it prints as many lines as there are in z. I essentially want it toi compare every row in z against every row in s but it only does it for the first row in z and exits

import csv
if __name__ == "__main__":

    with open("z_file.csv", "r") as f:
        with open("s_file.csv", "r") as g:
            with open("results.csv", "a+", newline="") as h:
                z = csv.reader(f)
                s = csv.reader(g)
                final = csv.writer(h)
                i = 0
                for zrow in z:
                    i += 1
                    for srow in s:
                        print(i)
4
  • Once you’ve looped through s the first time it is done. You can’t loop through an iterator twice. You’ll need to save it to a proper list.
    – Mark
    Oct 28, 2019 at 15:41
  • 1
    @MarkMeyer - ooop! I guess we were typing at the same time.
    – mhhollomon
    Oct 28, 2019 at 15:47
  • @mhhollomon I would have made a proper answer, but I just have an iPad here — too hard to type.
    – Mark
    Oct 28, 2019 at 15:51
  • Not an error, but you can consolidate multiple with statements on one line. with open("z_file.csv", "r") as f, open("s_file.csv", "r") as g: to save yourself an indent level
    – SyntaxVoid
    Oct 28, 2019 at 16:41

1 Answer 1

2

The first time you hit the inner loop, all line lines are read from the file. On the second iteration of the outer loop, the reading doesn't start over, it takes up where it left off - at the end. z is not an array of lines, it is a lazy generator.

The easiest solution is to simply move the file open into the outer loop. So that it gets reopened in every iteration.

Faster, would be to actually read it into a list and iterate over the list.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.