readline in while loop

laotseu bdesth at removethis.free.fr
Fri May 23 10:48:03 EDT 2003


Geert Fannes wrote:
> hello, i tried to construct a program to read a file, line after line. i 
> have no idea why it does not work...
> 
> f=file("test.txt","r");
> while l=f.readline():
>     print l;
> 
> the problem is with "while l=f.readline():" the next program does work
> 
> f=file("test.txt","r");
> while f.readline():
> 
> i tried things like
> 
> f=file("test.txt","r");
> while (l=f.readline())!="":
>     print l;
> 
> but that doesn't work either. 

It doesn't work because Python is not C. In Python, an assignation is a 
statement, not an expression, so it don't have a value.

You could (should ?) use the 'readlines()' method 
          -
f = file("test.txt", "r")
lines = f.readlines()
f.close()

for line in lines:
     print line


BTW, dont use 'l' as an identifier, unless you want to obfuscate your 
code (but then Python might not be the best language...)

Laotseu





More information about the Python-list mailing list