Get last n lines of a file, similar to tail

前端 未结 30 2496
挽巷
挽巷 2020-11-22 03:46

I\'m writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest

30条回答
  •  名媛妹妹
    2020-11-22 04:09

    you can go to the end of your file with f.seek(0, 2) and then read off lines one by one with the following replacement for readline():

    def readline_backwards(self, f):
        backline = ''
        last = ''
        while not last == '\n':
            backline = last + backline
            if f.tell() <= 0:
                return backline
            f.seek(-1, 1)
            last = f.read(1)
            f.seek(-1, 1)
        backline = last
        last = ''
        while not last == '\n':
            backline = last + backline
            if f.tell() <= 0:
                return backline
            f.seek(-1, 1)
            last = f.read(1)
            f.seek(-1, 1)
        f.seek(1, 1)
        return backline
    

提交回复
热议问题