how do I "peek" into the next line?

Adam DePrince adam at cognitcorp.com
Mon Dec 13 23:25:55 CET 2004


On Mon, 2004-12-13 at 16:24, les_ander at yahoo.com wrote:
> OK, I am sorry , I did not explain my problem completely.
> I can easily break from the loop when I see the character in a line
> that I just read; however my problem involves putting back the line I
> just read since if I have seen this special character, I have read one
> line too many. Let me illustrate
> suppose the file has 3 lines
> 
> line1.line1.line1
> >line2.line2.line
> line3.line3.line3
> 
> now suppose I have read the first line already.
> then I read the second line and notice
> that there is a ">" in front (my special character)
> then I want the put back the second line into the
> file or the stdin.
> 
> An easy way is if i read all the lines in to an array
> and then I can put back the line with the special
> character back into this array. However,
> this file I am readding is huge! and I can read
> it all in one swoop (not enough memory).
> 
> for x in stdin:
> if x[0]==">":
> #### put back the x some how... <-----
> break
>   else:
>       print x
> 
> I hope this is clear
> thanks

class stackfile:
    def __init__( self, f ):
        self.f = f
        self.stack = []

    def readline( self ):
        if len( self.stack ):
            return self.stack.pop()
        return self.f.readline()

    def unreadline( self, lastline ):
        self.stack.append( lastline )



if __name__=="__main__":
    import StringIO

    f = stackfile(StringIO.StringIO("a\nb\nc\nd\ne\nf\ng\n"))
    # You would say: myfile = stackfile( stdin ) 

    line = f.readline()
    print line,
    
    line = f.readline()
    print line,
    
    line = f.readline()
    print line,

    f.unreadline( line )
    
    line = f.readline()
    print line,

    line = f.readline()
    print line,

Running this prints:

a
b
c
c
d

Hope this helps.


Adam DePrince 





More information about the Python-list mailing list