Looping issues

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Apr 5 16:28:32 EDT 2007


brochu121 at gmail.com a écrit :
> What I am trying to do is compare two files to each other.
> 
> If the 2nd file contains the same line the first file contains, I want
> to print it. I wrote up the following code:
> 
> 
> 
> correct_settings = open("C:\Python25\Scripts\Output
> \correct_settings.txt","r")
> current_settings = open("C:\Python25\Scripts\Output\output.txt","r")
> 
> for line in correct_settings:
>         for val in current_settings:
>             if val == line:
>                 print line + " found."
> 
> 
> correct_settings.close()
> current_settings.close()
> 
> 
> For some reason this only looks at the first line of the
> correct_settings.txt file.

Not quite. It really go thru the whole file. But it only enter the inner 
loop for the first line. Then the file iterator is exhausted, and the 
other iterations are noop. You can verify this by adding a couple print 
statements - one in the outer loop and one in the inner one.

> Any ideas as to how i can loop through each
> line of the correct_settings file instead of just looking at the first?
> 
The good question is "how to loop thru the lines of *current_*settings 
for each line of correct_settings". The answer is : don't use the file 
iterator here, read the whole file in memory. Cf Larry's post for a howto.



More information about the Python-list mailing list