python 倒读 一个文件,从最后一行往前读

时间:2024-11-07 07:29:58
#!/usr/bin/env python
# -*-mode: python; coding: iso-8859-1 -*-
#
# Copyright (c) Peter Astrand <astrand@>

import os
import string

class BackwardsReader:
    """Read a file line by line, backwards"""
    BLKSIZE = 4096

    def readline(self):
        while 1:
            newline_pos = (, "\n")
            pos = ()
            if newline_pos != -1:
                # Found a newline
                line = [newline_pos+1:]
                = [:newline_pos]
                if pos != 0 or newline_pos != 0 or self.trailing_newline:
                    line += "\n"
                return line
            else:
                if pos == 0:
                    # Start-of-file
                    return ""
                else:
                    # Need to fill buffer
                    toread = min(, pos)
                    (-toread, 1)
                    = (toread) +
                    (-toread, 1)
                    if pos - toread == 0:
                        = "\n" +

    def __init__(self, file):
        = file
        = ""
        (-1, 2)
        self.trailing_newline = 0
        lastchar = (1)
        if lastchar == "\n":
            self.trailing_newline = 1
            (-1, 2)

if __name__=="__main__":
    br = BackwardsReader(open(''))
    for i in range(14):
        print ()