A few beginning questions

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Jul 15 16:11:02 CEST 2003

"richardc" <richardc at hmgcc.gov.uk> wrote in
news:3f13f674$1 at mail.hmgcc.gov.uk: 

> I wanted to scan the lines backwards until I found %%EOF (as its
> likley to be the last line) and do it that way.  I might do that or
> might use a regex and just let that find it.

Ok, try this. (On Windows systems the file has to be opened in binary mode 
for this to work.)

----- cut here -----
from __future__ import generators

def readbackwards(aFile, blocksize=1024):
    def blocks(length, blocksize):
        for pos in range(length, 0, -blocksize):
            yield pos, 1024
        yield 0, pos
    aFile.seek(0, 2) # Seek to end
    eof = aFile.tell()
    residue = None
    for pos, size in blocks(eof, blocksize):
        aFile.seek(pos, 0)
        block = aFile.read(blocksize)
        if residue is not None:
            block += residue
        lines = block.split('\n')

        residue = lines.pop()
        for line in lines:
            if line.endswith('\r'):
                line = line[:-1]
            yield line

    if residue is not None:
        yield residue

if __name__=='__main__':
    input = file('test.txt', 'rb')
    for line in readbackwards(input, blocksize=8192):
        if line.startswith("%%EOF"):
            print line

----- end cut ------

Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list