Get last n lines of a file, similar to tail

前端 未结 30 2893
挽巷
挽巷 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 Eyecue answer (Jun 10 '10 at 21:28): this class add head() and tail() method to file object.

    class File(file):
        def head(self, lines_2find=1):
            self.seek(0)                            #Rewind file
            return [self.next() for x in xrange(lines_2find)]
    
        def tail(self, lines_2find=1):  
            self.seek(0, 2)                         #go to end of file
            bytes_in_file = self.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)
                self.seek(-(byte_block+total_bytes_scanned), 2)
                total_bytes_scanned += byte_block
                lines_found += self.read(1024).count('\n')
            self.seek(-total_bytes_scanned, 2)
            line_list = list(self.readlines())
            return line_list[-lines_2find:]
    

    Usage:

    f = File('path/to/file', 'r')
    f.head(3)
    f.tail(3)
    

提交回复
热议问题