python讀取檔案最後n行

來源:互聯網
上載者:User
# -*- 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    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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.