Get last n lines of a file, similar to tail

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

    based on S.Lott's top voted answer (Sep 25 '08 at 21:43), but fixed for small files.

    def tail(the_file, lines_2find=20):  
        the_file.seek(0, 2)                         #go to end of file
        bytes_in_file = the_file.tell()             
        lines_found, total_bytes_scanned = 0, 0
        while lines_2find+1 > lines_found and bytes_in_file > total_bytes_scanned: 
            byte_block = min(1024, bytes_in_file-total_bytes_scanned)
            the_file.seek(-(byte_block+total_bytes_scanned), 2)
            total_bytes_scanned += byte_block
            lines_found += the_file.read(1024).count('\n')
        the_file.seek(-total_bytes_scanned, 2)
        line_list = list(the_file.readlines())
        return line_list[-lines_2find:]
    
        #we read at least 21 line breaks from the bottom, block by block for speed
        #21 to ensure we don't get a half line
    

    Hope this is useful.

提交回复
热议问题