readline in while loop

Steven Taschuk staschuk at telusplanet.net
Fri May 23 10:18:10 EDT 2003


Quoth Geert Fannes:
> 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;
  [...]

Python distinguishes between statements and expressions.
    l = f.readline()
is a statement (an assignment statement, to be specific), but
    while ... :
requires an expression.  (This is unlike C; one reason Python
works this way is to avoid this:
    while (x = 5) {  /* oops -- meant x == 5 */
This kind of error is common in C, and can be difficult to find.
Python helpfully tells you immediately that something is wrong.)

One way to do what you want is

    while 1:
        line = f.readline()
        if not line:
            break
        print line

But even better is

    for line in f:
        print line

which works because iterating over an open file provides the lines
in the file.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)





More information about the Python-list mailing list