Get last n lines of a file, similar to tail

前端 未结 30 3145
挽巷
挽巷 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 03:58

    An even cleaner python3 compatible version that doesn't insert but appends & reverses:

    def tail(f, window=1):
        """
        Returns the last `window` lines of file `f` as a list of bytes.
        """
        if window == 0:
            return b''
        BUFSIZE = 1024
        f.seek(0, 2)
        end = f.tell()
        nlines = window + 1
        data = []
        while nlines > 0 and end > 0:
            i = max(0, end - BUFSIZE)
            nread = min(end, BUFSIZE)
    
            f.seek(i)
            chunk = f.read(nread)
            data.append(chunk)
            nlines -= chunk.count(b'\n')
            end -= nread
        return b'\n'.join(b''.join(reversed(data)).splitlines()[-window:])
    

    use it like this:

    with open(path, 'rb') as f:
        last_lines = tail(f, 3).decode('utf-8')
    

提交回复
热议问题