how do I "peek" into the next line?

Jeffrey Maitland maitj at vianet.ca
Mon Dec 13 20:32:50 CET 2004


les_ander at yahoo.com writes: 

> Hi,
> 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:
> line=stdin.peek_nextline()
> if not line: break
> if line[0]=="|":
> break:
> else:
>     x=stdin.nextline()
>     # do something with x 
> 
> thanks 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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 

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:
    testline = file.readline()
    if re.match("#", testline) == True:
       break
    else:
       variablestr += testline 

file.close() 

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.. 

Jeff



More information about the Python-list mailing list