Python 读取日志文件在前端实现分页查询
?# -*- coding: utf-8 -*-import fileinputfilePath = 'd:/test.txt'page_size = 5 #每页显示的行数page_num = 1 #前端的当前页数current_num = 0 #从当前行数开始读取record_count = 0 #文件总数据条数flag = False #用来标记是否到了需读取的起始行号init_flag = True #是否为初次加载res = [] #结果集result = {'count' : 0, 'res' : []} #最终结果集if init_flag: ''' 如果前端是初次加载,init_flag = true, 计算文件总数,计算后将init_flag 置为false,下次翻页不再做总数统计 ''' temp_f = open(filePath, 'r') for count, line in enumerate(open(filePath, 'r')): record_count += 1 temp_f.close() init_flag = Falsefor eachline in fileinput.input(filePath): ''' 此部分用来读取需要显示部分的数据 ''' line_no = fileinput.filelineno() #当前读取的行号 if not flag: if line_no == (page_num - 1)*page_size + 1: flag = True if flag: if line_no > (page_num - 1)*page_size and line_no <= page_num*page_size: res.append(eachline) else: current_num = line_no fileinput.close(); break;result['count'] = record_countresult['res'] = resprint result
?# -*- coding: utf-8 -*-import fileinputfilePath = 'd:/test.txt'pagesize = 5 #每页显示的行数pageindex = 1 #前端的当前页数current_num = 0 #从当前行数开始读取record_count = 0 #文件总数据条数flag = False #用来标记是否到了需读取的起始行号init_flag = True #是否为初次加载res = [] #结果集result = {'count' : 0, 'res' : []} #最终结果集if init_flag: ''' 如果前端是初次加载,init_flag = true, 计算文件总数,计算后将init_flag 置为false,下次翻页不再做总数统计 ''' temp_f = open(filePath, 'r') for count, line in enumerate(open(filePath, 'r')): record_count += 1 temp_f.close() init_flag = Falsefor eachline in fileinput.input(filePath): ''' 此部分用来读取需要显示部分的数据 ''' line_no = fileinput.filelineno() #当前读取的行号 if not flag: if line_no == record_count - pageindex*pagesize + 1: flag = True if flag: if line_no >= record_count - pageindex*pagesize + 1 \ and line_no < record_count - (pageindex - 1)*pagesize + 1: res.append(eachline) else: fileinput.close(); break;result['count'] = record_countresult['res'] = resprint result