这篇文章主要介绍了python实现读取文件最后n行的方法,涉及python针对文件的读取、遍历与运算相关操作技巧,需要的朋友可以参考下
# -*- coding:utf8-*-import osimport timeimport datetimeimport mathimport stringdef 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 16732013-08-05 16:10:34 ok 16282013-08-05 16:11:55 ok 712013-08-05 16:13:02 ok 14412013-08-05 16:14:06 ok 16342013-08-05 16:15:10 ok 17172013-08-05 16:16:14 ok 16872013-08-05 16:17:18 ok 16422013-08-05 16:18:27 ok 16552013-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
登录后复制
【相关推荐】
1. Python免费视频教程
立即学习“Python免费学习笔记(深入)”;
2. Python在数据科学中的应用
3. Python学习手册
以上就是Python读取文件后n行的代码示例的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2273190.html