发布时间:2022-11-11 09:36:53 人气:133 作者:多测师
处理文件时,一个常见的需求就是读取文件的最后一行。那么这个需求用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
其中有几个注意点:
1. fp.seek(offset[, where])中where=0,1,2分别表示从文件头,当前指针位置,文件尾偏移,缺省值为0,但是如果要指定where=2,文件打开的方式必须是二进制打开,即使用'rb'模式,
2. 设置偏移量时注意不要超过文件总的字节数,否则会报OSError,
3. 注意边界条件的处理,比如文件只有一行的情况。
以上内容为大家介绍了python培训之怎么读文件最后几行,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/