Read file from bottom

Mike C. Fletcher mcfletch at rogers.com
Mon May 13 17:47:17 EDT 2002


Just as another approach (though the implementation is a little hacky, I 
whipped it off rather quickly and haven't refactored it).  For your 
actual project, you'd likely cache lines on reading them (splitting the 
read data on '\n', and adding the first block to the next read's 
results), then pass in a function to process each line checking for a match.

A sub-class could use these techniques to create a true reversible-file 
object (letting you do "fh.readline()" to get a particular line), but I 
don't have time today.

Anyway, for your consideration:


import os, stat
def tail( filename, count=2, mode = 'r', sentinel='\n', blocksize = 2048 ):
     size = os.stat( filename )[ stat.ST_SIZE ]
     cache = []
     currentCount = 0
     currentPosition = size
     fh = open(filename, mode )
     while currentCount < count:
         fh.seek( currentPosition-blocksize )
         new = fh.read( blocksize )
         currentCount = currentCount + new.count(sentinel)
         cache.append( new )
         currentPosition = currentPosition-blocksize
     cache = "".join( cache )
     currentCount = 0
     position = len( cache )
     while currentCount < count:
         position = cache.rindex( sentinel, 0, position )
         currentCount = currentCount + 1
     return cache[position:]


Enjoy,
Mike


Julia Bell wrote:
...

>>Julia Bell <julia.bell at jpl.nasa.gov> wrote:
>>
>>
>>>Is there an efficient (and relatively easy - I'm new to Python) way of
>>>reading the file from the last line backward instead of the first line
>>>forward?
>>
>>
>>tail | python script.py
>>
>>--
>>William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
>>8-CPU Cluster, Hosting, NAS, Linux, LaTeX, python, vim, mutt, tin
...

_______________________________________
   Mike C. Fletcher
   http://members.rogers.com/mcfletch/







More information about the Python-list mailing list