Need to unread or push back bytes to a file

Alex Martelli aleaxit at yahoo.com
Sat Feb 24 04:25:27 EST 2001


"Noah Spurrier" <noah(a)noah.org> wrote in message
news:9771ks0ic2 at news2.newsguy.com...
>
>
> I need to push bytes back into a file object.
> Is there a buffered file wrapper for file objects?
> (Yes, I looked, but I gave up after almost five minutes of searching.)
>
> I'm reading from a pipe, but this could be the same for a file.
> I call an "expect" method which reads until a pattern is found,
> but read() with a pipe will read as much data as there is available
> in the pipe. When I have found a pattern match I want to return
> the stream with the extra character pushed-back.

what about something like:

class NSWrapper:
    def __init__(self, fileob):
        self.fileob = fileob
        self.buffer = ''
    def close(self):
        self.fileob.close()
        self.buffer = ''
    def push_back(self, piece):
        self.buffer = piece + self.buffer
    def readall(self):
        result = self.buffer + self.fileob.read()
        self.buffer = ''
        return result
    def read(self, N=None):
        if N is None: return self.readall()
        avail = len(self.buffer)
        if N>avail:
            result = self.buffer+file.read(N-avail)
            self.buffer = ''
        else:
            result = self.buffer[:N]
            self.buffer = self.buffer[N:]
        return result

needs testing, but this should be roughly what you want...?


Alex






More information about the Python-list mailing list