import mmap import os def file_last(file, count): with open("log.txt") as log: end = last_pos = os.stat("log.txt").st_size lines = [] with mmap.mmap(log.fileno(), 0, access=mmap.ACCESS_READ) as mm: while last_pos != -1: last_pos = mm.rfind(b"\n", 0, last_pos) if last_pos != -1: lines.append(mm[last_pos:end].strip().decode()) end = last_pos if len(lines) >= count: break lines.reverse() return lines last_lines = file_last("log.txt", 3) for line in last_lines: print(line)