1 ## {{{ http://code.activestate.com/recipes/439045/ (r2)
3 # -*-mode: python; coding: iso-8859-1 -*-
5 # Copyright (c) Peter Astrand <astrand@cendio.se>
11 class BackwardsReader
:
12 """Read a file line by line, backwards"""
16 newline_pos
= string
.rfind(self
.buf
, "\n")
17 pos
= self
.file.tell()
20 line
= self
.buf
[newline_pos
+1:]
21 self
.buf
= self
.buf
[:newline_pos
]
22 if pos
!= 0 or newline_pos
!= 0 or self
.trailing_newline
:
31 toread
= min(self
.BLKSIZE
, pos
)
32 self
.file.seek(-toread
, 1)
33 self
.buf
= self
.file.read(toread
) + self
.buf
34 self
.file.seek(-toread
, 1)
36 self
.buf
= "\n" + self
.buf
38 def __init__(self
, file, BLKSIZE
=4096):
40 self
.BLKSIZE
= BLKSIZE
43 self
.trailing_newline
= 0
44 lastchar
= self
.file.read(1)
46 self
.trailing_newline
= 1