[Tutor] Problem with nested for-in

Alan Gauld alan.gauld at btinternet.com
Thu Jan 29 13:17:24 CET 2009

"emmanuel.delaborde" <emmanuel.delaborde at cimex.com> wrote

> I have the following snippet :
> lines = csv.reader(open("CATEGORY.csv","r"))
> lines2 = csv.reader(open("CATEGORYLIST.csv","r"))
> old_cats = []
> for line in lines:
>     stories = []
>     for line2 in lines2:
>         if line2[1] == line[0]:
>             stories.append(line2[0])
>     old_cats.append((line[0],line[2], stories))
> what happens is that
> for the first elt of lines, the nested for in runs fine
> but then never seem to run again while the top level loop iterates 
> through the rest of lines

I suspect that you need to reset the reader iterator to the start.
I'm sure there will be something in the iterator protocol to do
that but failing that you would need to change the inner loop to:

for line2 in csv.reader(open("CATEGORYLIST.csv","r"))

which will re-read the file and create a new iterator each time...
resetting the iterator would be faster I suspect.

Alan G. 

More information about the Tutor mailing list