当前位置:首页 > 云计算 > 正文内容

python怎么读文件最后几行

2022-05-04 03:00:18云计算4

处理文件时,一个常见的需求就是读取文件的最后一行。那么这个需求用python怎么实现呢?一个朴素的想法如下:

withopen('a.log','r')asfp:
lines=fp.readlines()
last_line=lines[-1]

即使不考虑异常处理的问题,这个代码也不完美,因为如果文件很大,lines = fp.readlines()会造成很大的时间和空间开销。

解决的思路是用将文件指针定位到文件尾,然后从文件尾试探出一行的长度,从而读取最后一行。代码如下:

def__get_last_line(self,filename):
"""
getlastlineofafile
:paramfilename:filename
:return:lastlineorNoneforemptyfile
"""
try:
filesize=os.path.getsize(filename)
iffilesize==0:
returnNone
else:
withopen(filename,'rb')asfp:#touseseekfromend,mustusemode'rb'
offset=-8#initializeoffset
while-offset<filesize:#offsetcannotexceedfilesize
fp.seek(offset,2)#read#offsetcharsfromeof(representbynumber'2')
lines=fp.readlines()#readfromfptoeof
iflen(lines)>=2:#ifcontainsatleast2lines
returnlines[-1]#thenlastlineistotallyincluded
else:
offset*=2#enlargeoffset
fp.seek(0)
lines=fp.readlines()
returnlines[-1]
exceptFileNotFoundError:
print(filename+'notfound!')
returnNone

其中有几个注意点:

1. fp.seek(offset[, where])中where=0,1,2分别表示从文件头,当前指针位置,文件尾偏移,缺省值为0,但是如果要指定where=2,文件打开的方式必须是二进制打开,即使用'rb'模式,

2. 设置偏移量时注意不要超过文件总的字节数,否则会报OSError,

3. 注意边界条件的处理,比如文件只有一行的情况。

本网站文章仅供交流学习 ,不作为商用, 版权归属原作者,部分文章推送时未能及时与原作者取得联系,若来源标注错误或侵犯到您的权益烦请告知,我们将立即删除.

本文链接:https://www.xibujisuan.cn/2936.html

标签: Python