0

I have 2 for loops inside of a with open statement. The first for loop runs perfectly, but it seems that the 2nd for loop is not ran. Sample code below. Can someone explain why the second for loop is skipped over?

with open(data, 'r') as csvFile:
   csvReader = csvReader.csvreader(csvFile, delimiter = ',')
   counter1 = 0
   for row in csvReader:
      counter1 = counter1 + 1
   print(counter1)

   counter2 = 0
   for row in csvReader:
      counter2 = counter2 + 1
   print(counter2)

I know how to write the above code as a single for loop, however I cannot figure out why the second for loop is being ignored. Any suggestions would be much appreciated. Thanks!

jth359
  • 779
  • 1
  • 8
  • 10
  • 1
    `csvReader` has been iterated through. After the first `for` loop, you are already at the end of the `Reader` object. – pstatix Jan 04 '18 at 02:01
  • 1
    second iteration will not go through after the first for loop consumes the reader. – skrubber Jan 04 '18 at 02:02

2 Answers2

2

What happened here is the first loop consumed the csvReader generator

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:

taoufik A
  • 1,439
  • 11
  • 20
0

I am going to assume you are using the standard libraries csv module:

counter1 = 0
counter2 = 0

with open(data, 'r') as f:
   reader = csv.Reader(f, delimiter = ',')
   rows = list(reader)

    for row in rows:
        counter1 += 1
    print(counter1)

    for row in rows:
        counter2 += 1
    print(counter2)

By turning the Reader object into a list, you can iterate over it endlessly. However, given the function of these for loops, you are better off pulling them out from within the with and letting context close since you really dont need the file open to perform their operations.

pstatix
  • 3,611
  • 4
  • 18
  • 40