how do I "peek" into the next line?
maitj at vianet.ca
Mon Dec 13 20:36:48 CET 2004
Jeffrey Maitland writes:
> les_ander at yahoo.com writes:
>> suppose I am reading lines from a file or stdin.
>> I want to just "peek" in to the next line, and if it starts
>> with a special character I want to break out of a for loop,
>> other wise I want to do readline().
>> Is there a way to do this?
>> for example:
>> while 1:
>> if not line: break
>> if line=="|":
>> # do something with x
> Well what you can do is read the line regardless into a testing variable.
> here is some sample code (writting this off the topof my head so syntax
> might be off some)
> import re
> file = open("test.txt", 'r')
> variablestr = '' #this would be your object.. in my example using a string
> for the file data
> eof = file.tell() #what this is the position of the end of the file.
> while file.tell() != eof:
> testline = file.readline()
> if re.match("#", testline) == True:
> variablestr += testline
> now if I was concerned with being at the beging of the testline that it
> read in what you can do is in the if is something like:
> file.seek((file.tell() - len(testline)), 0)
> and that will move you back to the beginging of that line which is where
> the readline from the previous call left you before the "peek".
> hope that helps some..
I noticed something in my code.
re.match("#", testline) == True isn't possible it would be more like.
re.match("#", testline) != None
More information about the Python-list