Python實(shí)現(xiàn)讀取文件最后n行的方法
本文實(shí)例講述了Python實(shí)現(xiàn)讀取文件最后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
#獲取最后一行的結(jié)果
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 '數(shù)據(jù)條數(shù)正常'
print 'OK'
else:
print '數(shù)據(jù)太少,檢查發(fā)郵件'
以上處理和日志文件格式為
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
讀取最后一行:
#返回文件最后一行函數(shù) 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
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python實(shí)現(xiàn)完全數(shù)的示例詳解
完全數(shù),又稱完美數(shù),定義為:這個(gè)數(shù)的所有因數(shù)(不包括這個(gè)數(shù)本身)加起來剛好等于這個(gè)數(shù)。本文就來用Python實(shí)現(xiàn)計(jì)算完全數(shù),需要的可以參考一下2023-01-01
Python 實(shí)現(xiàn)二叉查找樹的示例代碼
這篇文章主要介紹了Python 實(shí)現(xiàn)二叉查找樹的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
Python實(shí)現(xiàn)郵件的批量發(fā)送的示例代碼
下面小編就為大家分享一篇Python實(shí)現(xiàn)郵件的批量發(fā)送的示例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01
python3基于OpenCV實(shí)現(xiàn)證件照背景替換
這篇文章主要為大家詳細(xì)介紹了python3基于OpenCV實(shí)現(xiàn)證件照背景替換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
兩個(gè)命令把 Vim 打造成 Python IDE的方法
這篇文章主要介紹了兩個(gè)命令把 Vim 打造成 Python IDE,需要的朋友可以參考下2016-03-03
Python關(guān)于excel和shp的使用在matplotlib
今天小編就為大家分享一篇關(guān)于Python關(guān)于excel和shp的使用在matplotlib,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
python中main函數(shù)(主函數(shù))相關(guān)應(yīng)用例子
這篇文章主要介紹了python中main函數(shù)(主函數(shù))相關(guān)應(yīng)用,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05

