登录  /  注册

Python读取文件后n行的代码示例

Y2J
发布: 2017-05-08 16:37:00
原创
2008人浏览过

这篇文章主要介绍了python实现读取文件最后n行的方法,涉及python针对文件的读取、遍历与运算相关操作技巧,需要的朋友可以参考下

# -*- 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
登录后复制

【相关推荐】

1. Python免费视频教程

2. Python在数据科学中的应用

3. Python学习手册

以上就是Python读取文件后n行的代码示例的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号