Problem while reading a text file in reverse order.

Srihari Vijayaraghavan harisri at bigpond.com
Wed May 1 03:50:34 EDT 2002


Hello,

As you know, on a given (same) file object (text file with '\r\n')
read() method hides the '\r' on Windows, but not on Linux. But it
counts for seek() method on both platforms.

I am trying to write a GNU 'tac' like utility to use on both Linux and
Windows. The following script works fine on Linux for both '\n' and
'\r\n'. But on Windows it works for '\n' and not quite right for
'\r\n'.

#!/usr/bin/python
import sys, cStringIO
def tac(data):
    data.seek(0, 2)
    while 1:
        size = data.tell()
        if size >= 512:
            data.seek(-512, 1)
            temp = data.read(512)
            data.seek(-512, 1)
            #print 512-len(temp)
            next_newline = temp.index('\n')
            data.seek(next_newline+1, 1)
            result = cStringIO.StringIO(temp[next_newline+1:])
            all_lines = result.readlines()
            all_lines.reverse()
            for everyline in all_lines:
                print everyline,
        elif size > 0 and size < 512:
            position = data.tell()
            data.seek(0)
            temp = data.read(position)
            result = cStringIO.StringIO(temp)
            all_lines = result.readlines()
            all_lines.reverse()
            for everyline in all_lines:
                print everyline,
            break
        elif size == 0:
            break
def main():
    data = open(sys.argv[1], 'r')
    tac(data)
if __name__ == '__main__': main()

(I guess you will get the number of 'vapourising' '\r' if you enable
the commented 'print' statement)

Is there a way to enable '\r' for read() method on Windows, or to code
it intelligently :-) to handle it. (by means of either completely not
caring about line feeds, or accounting '\r')

Wouldn't it be wonderful if python provided readline() like method
(perhaps reverse_readline() :-)) for reading files in reverse order?
(for at least file objects)

Please ask me if you need a sample file based on '\r\n'.

Thanks for your time,

Hari,
harisri at bigpond.com



More information about the Python-list mailing list