how do I "peek" into the next line?

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


Jeffrey Maitland wrote:

> file.seek(0,2)
> eof = file.tell() #what this is the position of the end of the file.
> file.seek(0,0)
>
> 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] == "#":
          break

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("#"):
        break

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

(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

</F> 






More information about the Python-list mailing list