最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

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

来源:懂视网 责编:小采 时间:2020-11-27 14:24:26
文档

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

Python读取文件后n行的代码示例:这篇文章主要介绍了Python实现读取文件最后n行的方法,涉及Python针对文件的读取、遍历与运算相关操作技巧,需要的朋友可以参考下# -*- coding:utf8-*- import os import time import datetime import math import string de
推荐度:
导读Python读取文件后n行的代码示例:这篇文章主要介绍了Python实现读取文件最后n行的方法,涉及Python针对文件的读取、遍历与运算相关操作技巧,需要的朋友可以参考下# -*- coding:utf8-*- import os import time import datetime import math import string de

这篇文章主要介绍了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行的代码示例

Python读取文件后n行的代码示例:这篇文章主要介绍了Python实现读取文件最后n行的方法,涉及Python针对文件的读取、遍历与运算相关操作技巧,需要的朋友可以参考下# -*- coding:utf8-*- import os import time import datetime import math import string de
推荐度:
标签: 文件 File 文件的
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top