python 查看文件最新的几行
import linecache def get_line_count(filename): count = 0 with open(filename, 'r') as f: while True: buffer = f.read(1024 * 1) if not buffer: break count += buffer.count('\n') return count def error_log(): # 读取最后100行 file = 'log_error.out' n = 100 linecache.clearcache() line_count = get_line_count(file) print('num: ', line_count) line_count_start = line_count - (n - 1) if line_count_start < 0: n = line_count + 1 line_count_start = 0 all_line = [] for i in range(n): last_line = linecache.getline(file, line_count_start) # print(line_count_start, last_line) all_line.append(last_line) line_count_start += 1 return "".join(all_line) if __name__ == '__main__': print(error_log())