Get last n lines of a file, similar to tail

前端 未结 30 2922
挽巷
挽巷 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:25

    Update @papercrane solution to python3. Open the file with open(filename, 'rb') and:

    def tail(f, window=20):
        """Returns the last `window` lines of file `f` as a list.
        """
        if window == 0:
            return []
    
        BUFSIZ = 1024
        f.seek(0, 2)
        remaining_bytes = f.tell()
        size = window + 1
        block = -1
        data = []
    
        while size > 0 and remaining_bytes > 0:
            if remaining_bytes - BUFSIZ > 0:
                # Seek back one whole BUFSIZ
                f.seek(block * BUFSIZ, 2)
                # read BUFFER
                bunch = f.read(BUFSIZ)
            else:
                # file too small, start from beginning
                f.seek(0, 0)
                # only read what was not read
                bunch = f.read(remaining_bytes)
    
            bunch = bunch.decode('utf-8')
            data.insert(0, bunch)
            size -= bunch.count('\n')
            remaining_bytes -= BUFSIZ
            block -= 1
    
        return ''.join(data).splitlines()[-window:]
    

提交回复
热议问题