how do I "peek" into the next line?

Fredrik Lundh fredrik at
Mon Dec 13 21:07:22 CET 2004

Jeffrey Maitland wrote:

> eof = file.tell() #what this is the position of the end of the file.
> while file.tell() != eof:

no no no.  that's not how you read all lines in a text file -- in any
programming language.

in recent versions of Python, use:

    for testline in file:

to loop over all lines in a given file.

>    if re.match("#", testline) == True:
>       break

ahem.  RE's might be nice, but using them to check if a string
starts with a given string literal is a pretty lousy idea.

      if testline[0] == "#":

works fine in this case (when you use the for-loop, at least).

if testline might be empty, use startswith() or slicing:

    if testline.startswith("#"):

    if testline[:1] == "#":

(if the thing you're looking for is longer than one character, startswith
is always almost the best choice)

if you insist on using a RE, you should use a plain if statement:

    if re.match(pattern, testline):
        break # break if it matched


More information about the Python-list mailing list