Monday, August 4, 2014

Read a file backwards in Python

Below sample Python code is just one of the possible implementations for reading a file in reverse order. It's not that efficient as it reads the file one character at a time but does the job; especially, what you are looking is towards the end of the file and/or file is not too big.

import os

def ReverseRead(fname, separator=os.linesep):
    with file(fname) as f:
        f.seek(0, 2)  # seek to the end of the file
        fsize = f.tell()  # get file size
        r_cursor = 1
        while r_cursor <= fsize:
            a_line = ''
            while r_cursor <= fsize:
                f.seek(-1 * r_cursor, 2)
                r_cursor += 1
                c = f.read(1)
                if c == separator and a_line:
                    r_cursor -= 1
                    break
                a_line += c
            a_line = a_line[::-1]
            yield a_line

It's a generator function so it can be used in a loop. By default, it returns one line at each call. Here's a sample use of the code.

File to read: a.txt

$ cat delete
Line1: a b   c d
Line2:         z
Line3:

Reading the file one line at a time in reverse order:

>>> for i in ReverseRead('a.txt'):
...   print i,
...
Line3:
Line2:         z
Line1: a b   c d
>>>