Is reverse reading possible?

Jeff Epler jepler at unpythonic.net
Sun Mar 14 19:01:05 CET 2004


on seekable, byte-oriented binary files, sure.

import errno

SEEK_SET, SEEK_CUR, SEEK_END = range(3)

class Reversed:
    def __init__(self, f):
        self.f = f
        self.f.seek(-1, SEEK_END)
        self.at_eof = 0

    def read_byte(self):
        if self.at_eof: return ''
        byte = self.f.read(1)
        try:
            self.f.seek(-2, SEEK_CUR)
        except IOError, detail:
            if detail.errno == errno.EINVAL:
                self.at_eof = 1
            else:
                raise
        return byte

    def __iter__(self): return self

    def next(self):
        r = self.read_byte()
        if r == '': raise StopIteration
        return r

>>> "".join(Reversed(file("/etc/redhat-release", "rb")))
'\n)worraY( 1 esaeler eroC arodeF'

Jeff




More information about the Python-list mailing list