处理文件时,一个常见的需求就是读取文件的最后一行。那么这个需求用python怎么实现呢?一个朴素的想法如下:
with open('a.log', 'r') as fp:
lines = fp.readlines()
last_line = lines[-1]
即使不考虑异常处理的问题,这个代码也不完美,因为如果文件很大,lines = fp.readlines()会造成很大的时间和空间开销。
解决的思路是用将文件指针定位到文件尾,然后从文件尾试探出一行的长度,从而读取最后一行。代码如下:
def __get_last_line(self, filename):
"""
get last line of a file
:param filename: file name
:return: last line or None for empty file
"""
try:
filesize = os.path.getsize(filename)
if filesize == 0:
return None
else:
with open(filename, 'rb') as fp: # to use seek from end, must use mode 'rb'
offset = -8 # initialize offset
while -offset < filesize: # offset cannot exceed file size
fp.seek(offset, 2) # read # offset chars from eof(represent by number '2')
lines = fp.readlines() # read from fp to eof
if len(lines) >= 2: # if contains at least 2 lines
return lines[-1] # then last line is totally included
else:
offset *= 2 # enlarge offset
fp.seek(0)
lines = fp.readlines()
return lines[-1]
except FileNotFoundError:
print(filename + ' not found!')
return None
其中有几个注意点:
原文连接:python读取文件最后一行