處理文件時(shí),一個(gè)常見的需求就是讀取文件的最后一行。那么這個(gè)需求用python怎么實(shí)現(xiàn)呢?一個(gè)樸素的想法如下:
withopen('a.log','r')asfp:
lines=fp.readlines()
last_line=lines[-1]
即使不考慮異常處理的問(wèn)題,這個(gè)代碼也不完美,因?yàn)槿绻募艽螅琹ines=fp.readlines()會(huì)造成很大的時(shí)間和空間開銷。
解決的思路是用將文件指針定位到文件尾,然后從文件尾試探出一行的長(zhǎng)度,從而讀取最后一行。代碼如下:
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 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 其中有幾個(gè)注意點(diǎn): 1.fp.seek(offset[,where])中where=0,1,2分別表示從文件頭,當(dāng)前指針位置,文件尾偏移,缺省值為0,但是如果要指定where=2,文件打開的方式必須是二進(jìn)制打開,即使用'rb'模式, 2.設(shè)置偏移量時(shí)注意不要超過(guò)文件總的字節(jié)數(shù),否則會(huì)報(bào)OSError, 3.注意邊界條件的處理,比如文件只有一行的情況。 以上內(nèi)容為大家介紹了python培訓(xùn)之怎么讀文件最后幾行,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。