国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現讀取文件最后n行的方法

2020-02-23 04:22:42
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現讀取文件最后n行的方法。分享給大家供大家參考,具體如下:

# -*- 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

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結》、《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 韩城市| 邳州市| 台南县| 禄丰县| 芦山县| 错那县| 浮山县| 仪征市| 开封市| 荥经县| 安乡县| 嵊泗县| 铁力市| 锡林浩特市| 南岸区| 利川市| 陈巴尔虎旗| 吉林省| 噶尔县| 河北区| 上栗县| 柳州市| 保德县| 宝丰县| 丰顺县| 合阳县| 昌都县| 灵山县| 黎川县| 长春市| 油尖旺区| 丹东市| 宁南县| 壶关县| 章丘市| 宾川县| 阿克| 任丘市| 大洼县| 乌拉特中旗| 武宁县|