Use Python to read the first line (the first row) and the last line (the final row) of the file (for large files and two small files). The script draws on the previous two processing ideas (in the script below to illustrate the source of references), and fixed the original two processing methods if the end of the file contains multiple empty lines and return empty rows.
The contents of the script can be obtained from GitHub:
https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/file/getFileLastLine.py
The script reads as follows:
#!/usr/bin/python# encoding: utf-8# -*- coding: utf8 -*-"" "Created by pycharm.file: linuxbashshellscriptforops:getfilelastline.pyuser: guodongcreate date: 2016/9/ 1create time: 11:05 "" "Import os# Refer: http://www.pythonclub.org/python-files/last-linedef get_last_line (inputfile): filesize = os.path.getsize (inputfile) blocksize = 1024 dat_file = open (inputfile, ' RB ') 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# Refer: http://code.activestate.com/recipes/578095/def print_first_last_line (inputfile): filesize = os.path.getsize (inputfile) blocksize = 1024 dat_file = open (inputfile, ' RB ') headers = dat_file.readline (). Strip () if filesize > blocksize: maxseekpoint = (filesize // blocksize) dat_ File.seek (maxseekpoint * blocksize) elif filesize: maxseekpoint = blocksize % filesize dat_file.seek (Maxseekpoint) lines = dat_ File.readlines () if lines: last_ Line = lines[-1].strip () # print "first line : ", headers # print "last line : ", last_line return headers,&nbSp;last_line# my implementationdef get_file_last_line (inputfile): Filesize = os.path.getsize (inputfile) blocksize = 1024 with open (inputfile, ' RB ') as f: last_line = "" if filesize > blocksize: maxseekpoint = ( Filesize // blocksize) f.seek ((maxseekpoint - 1) * blocksize) elif Filesize: f.seek (0, 0) lines = f.readlines () if lines: lineno = 1 while last_line == "": last_line = lines[- Lineno].strip () lineno += 1 return last_line# test purpose# print get_last_line (Os.path.abspath (__file__)) # print print_first_last_line (Os.path.abspath (__file__)) # print get_file_last_line (Os.path.abspath (__file__))
--end--
This article is from "Communication, My Favorites" blog, please make sure to keep this source http://dgd2010.blog.51cto.com/1539422/1845139
Python reads the last line of the file (not a blank line)