reading line by line

Fredrik Lundh fredrik at effbot.org
Sun Jan 14 08:51:05 EST 2001


Michael P. Soulier wrote:
> file = open(filename, "r")
> line = file.readline()
> while line:
>     # work on file
>     line = file.readline()
>
>     But I don't like the initial readline() call to initialize line. It just
> doesn't look clean to me. Is there a better way, syntactically, to
> do this?

The standard pydiom is:

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

In the current cvs version, you can also use:

    for line in file.xreadlines():
        ...

where xreadlines is a lazy version of readlines (cf. xrange)

Cheers /F





More information about the Python-list mailing list