Nested loop

Juho Schultz juho.schultz at helsinki.fi
Wed Nov 30 03:22:33 EST 2005


viewcharts wrote:
> I am reading two text files comparing the values in one to the other, 
> this requires two loops. The problem is that when the inner loop is 
> finished, it never goes back into the loop. Any suggestions?
> 
> 
> for refSymbol in symbols.readlines():
>     for lookupSymbol in myfile.readlines(): 
>         showme = lookupSymbol.split('\t')
>         if showme[3] == refSymbol.strip():
>             priceNew.write(refSymbol.strip()+" "+showme[10])
> 
> 
> 

When the inner loop is finished for the 1st time,
myfile has been read. So next time you start to the
loop, myfile.readlines() returns an empty list.

Something like this should be better:

lookupSymList = myfile.readlines()
for refSymbol in symbols.readlines():
      for lookupSymbol in lookupSymList:
          showme = lookupSymbol.split('\t')
          if showme[3] == refSymbol.strip():
              priceNew.write(refSymbol.strip()+" "+showme[10])



More information about the Python-list mailing list