Python implements the method of reading the last n line of the file

  • 2020-05-26 09:35:10
  • OfStack

This article illustrates how the Python implementation reads the last n line of the file. I will share it with you for your reference as follows:


# -*- 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
# To obtain the final 1 The results of 
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 ' The number of data bars is normal '
     print 'OK'
  else:
     print ' Too little data, check email '

The above processing and log file format is


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

Read the last 1 line:


# Back to the file 1 Line function 
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

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article has been helpful to you in Python programming.


Related articles: