Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested For loops with python and csv

Tags:

python

loops

csv

I am having issues coding a nested for loop with csv objects in python. I want to parse both csv files and compare parts of them. Therefore I coded the nested loop below. What I expect is that the python parses the inner loop for the first item of the outer loop and then for the second item of the outer loop he parses again the inner loop and so on. Whats happening is, the inner loop gets parsed and then the outer loop gets passed without even entering the inner loop again.

When using non csv objects like num_list = [1, 2, 3] this works like expected.

Thanks.

import csv

csvfile = open('/Users/rene/Downloads/Test/Export.csv', newline='', encoding='windows-1252')
spamreader = csv.reader(csvfile, dialect='excel', delimiter=';')

csvfile1 = open('/Users/rene/Downloads/Test/Transfer.csv', newline='', encoding='windows-1252')
spamreader1 = csv.reader(csvfile1, dialect='excel', delimiter=';')

for row in spamreader:
    print("1row:"+row[1])
    for row1 in spamreader1:
        print("2row:"+row[1])
        print("2row1:"+row1[0])

csvfile.close()
csvfile1.close()
like image 255
Rene Avatar asked Mar 19 '26 16:03

Rene


1 Answers

The csv.reader objects are iterators that get exhausted when they are consumed. Hence, spamreader1 is already empty after the first iteration of the outer loop.

Simply turn spamreader1, which you iterate in the inner loop, into a list so you can iterate it multiple times:

# ...
# collect all rows in a list
spamreader1 = list(csv.reader(csvfile1, dialect='excel', delimiter=';'))

for row in spamreader:
    # ...
    for row1 in spamreader1:
        # now this will work as you expect
like image 90
user2390182 Avatar answered Mar 22 '26 05:03

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!