what is wrong with this line? while (line = workfile.readline()) != "":

Alex Martelli aleaxit at yahoo.com
Tue May 22 12:10:04 EDT 2001


"Samuel A. Falvo II" <kc5tja at dolphin.openprojects.net> wrote in message
news:slrn9gl22q.5c8.kc5tja at dolphin.openprojects.net...
> On Tue, 22 May 2001 09:14:41 -0600, erudite wrote:
> >Hey,
> >    I'm coming from the Java world to the python world which is probably
why
> >I'm a little confused as to why this statement doesn't work:
> >
> >while (line = workfile.readline()) != "":
>
> Python doesn't allow full expressions inside its control constructs.  What

Not sure what you mean by "full expression".  Any Python expression
is allowed in a "control structure".  The issue is, rather, that
assignment is *NOT* an expression in Python -- it's a statement.

> you probably meant to say is this:
>
> line = workfile.readline()
> while line != "":
>   srnsSearchReplace(line)
>   line = workfile.readline()
> workfile.close()

The usual Python idiom for this, to avoid repeating
the .readline call in two places, used to be:
    while 1:
        line = workfile.readline()
        if not line: break
        srnsSearchReplace(line)

Now that Python 2.1 is out, we have a better way:

    for line in workfile.xreadlines():
        srnsSearchReplace(line)

You can use .readlines(), instead of .xreadlines(), in any
Python version, but that may work badly if the file is truly
huge (on the order of magnitude of available memory).


Alex






More information about the Python-list mailing list