處理文件時,一個常見的需求就是讀取文件的最后一行。那么這個需求用python怎么實現(xiàn)呢?一個樸素的想法如下:
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 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.設置偏移量時注意不要超過文件總的字節(jié)數(shù),否則會報OSError, 3.注意邊界條件的處理,比如文件只有一行的情況。 以上內(nèi)容為大家介紹了python培訓之怎么讀文件最后幾行,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。