2

Here is the code I was using to manipulate a CSV file. It is not entering the 2nd and 3rd for loops.

import csv
f=open("/Users/shivendraagrawal/Desktop/Training Dataset.csv","rU")
cr = csv.reader(f)
mapping={}
out={}
i=0
for row in cr:
      i=i+1
      mapping[row[0]]=0
      out[row[0]]=0
for row in cr:
      print "hi"
      mapping[row[0]]=mapping[row[0]]+row[5]
      if row[6]=="TRUE":
            out[row[0]]=out[row[0]]+1

for row in cr:
      print mapping[row[0]] +'  '+out[row[0]]

print i   
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Shivendra
  • 1,076
  • 2
  • 12
  • 26

2 Answers2

2

You're using the iterator more than once, but the iterators are single-shot only.

Just make a copy of the cr contents when reading it, and iterate through that:

cr_copy = [c for c in cr]
for row in cr_copy:

Or, there is a more Pythonic way to do that: you can clone the iterator three times by using the itertools.tee (see this post):

import itertools

cr1, cr2 = itertools.tee(cr)
for row in cr1:
     # first loop

for row in cr2:
     # secondloop
Community
  • 1
  • 1
Vladimir Sinenko
  • 4,629
  • 1
  • 27
  • 39
2

use f.seek(0) to rewind back after first and second loop e.g. before second loop:

f.seek(0)
for row in cr:
    # loop code 

Read: from Python doc code

Give it a try!!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Why are you rewinding back the 'f' object while I am iterating over 'cr'? And thanks a lot, it is working now. – Shivendra Sep 21 '13 at 07:43
  • @Shivendra I just learn the trick from linked page. through `cr` not reset. – Grijesh Chauhan Sep 21 '13 at 08:07
  • @Shivendra It's part of the way the `csv` module is designed. The position of the `reader` is linked to the position of the file pointer. Advancing your `reader` moves the file pointer forwards; moving the file pointer back again resets the `reader`. – Benjamin Hodgson Sep 21 '13 at 13:51
  • @poorsod Thanks as learner I posted this answer. Can you provide some link to read further. – Grijesh Chauhan Sep 21 '13 at 13:53
  • @GrijeshChauhan It's basically because CSV readers work on any iterable. Here are the docs on [file objects](http://docs.python.org/2/library/stdtypes.html#file-objects) and the way they iterate; here are the docs on [CSV readers](http://docs.python.org/2/library/csv.html#reader-objects). If you're using Python 3, file objects are implemented somewhat differently, though they expose the same interface. – Benjamin Hodgson Sep 21 '13 at 14:05