Python读取文件最后n行 Python实现读取文件最后n行的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python读取文件最后n行 Python实现读取文件最后n行的方法

design321   2021-03-24 我要评论
想了解Python实现读取文件最后n行的方法的相关内容吗,design321在本文为您仔细讲解Python读取文件最后n行的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,读取,文件,最后n行,下面大家一起来学习吧。

本文实例讲述了Python实现读取文件最后n行的方法。分享给大家供大家参考,具体如下:

# -*- coding:utf8-*-
import os
import time
import datetime
import math
import string
def get_last_line(inputfile) :
 filesize = os.path.getsize(inputfile)
 blocksize = 1024
 dat_file = open(inputfile, 'r')
 last_line = ""
 lines = dat_file.readlines()
 count = len(lines)
 if count>60:
   num=60
 else:
   num=count
 i=1;
 lastre = []
 for i in range(1,(num+1)):
   if lines :
     n = -i
     last_line = lines[n].strip()
     #print "last line : ", last_line
     dat_file.close()
     #print i
     lastre.append(last_line)
 return lastre
#获取最后一行的结果
re = get_last_line('../update/log/rtime/rtime20130805.log')
print len(re)
for n in re:
  strlist = n.split('  ')
  if strlist[1] == 'ok' and string.atoi(strlist[2])>1000:
     print '数据条数正常'
     print 'OK'
  else:
     print '数据太少,检查发邮件'

以上处理和日志文件格式为

2013-08-05 16:09:30  ok  1673
2013-08-05 16:10:34  ok  1628
2013-08-05 16:11:55  ok  71
2013-08-05 16:13:02  ok  1441
2013-08-05 16:14:06  ok  1634
2013-08-05 16:15:10  ok  1717
2013-08-05 16:16:14  ok  1687
2013-08-05 16:17:18  ok  1642
2013-08-05 16:18:27  ok  1655
2013-08-05 16:19:33  ok  1655

读取最后一行:

#返回文件最后一行函数
def get_last_line(inputfile) :
 filesize = os.path.getsize(inputfile)
 blocksize = 1024
 dat_file = open(inputfile, 'r')
 last_line = ""
 if filesize > blocksize :
   maxseekpoint = (filesize // blocksize)
   dat_file.seek((maxseekpoint-1)*blocksize)
 elif filesize :
   #maxseekpoint = blocksize % filesize
   dat_file.seek(0, 0)
 lines = dat_file.readlines()
 if lines :
   last_line = lines[-1].strip()
 #print "last line : ", last_line
 dat_file.close()
 return last_line

希望本文所述对大家Python程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们