Python 读取日志文件在前端兑现分页查询
Python 读取日志文件在前端实现分页查询
# -*- coding: utf-8 -*- import fileinput filePath = '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 = False for 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_count result['res'] = res print result
# -*- coding: utf-8 -*- import fileinput filePath = '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 = False for 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_count result['res'] = res print result