python读取文件最后一行
生活随笔
收集整理的這篇文章主要介紹了
python读取文件最后一行
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
處理文件時,一個常見的需求就是讀取文件的最后一行。那么這個需求用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 Noneelse:with open(filename 'rb') as fp: # to use seek from end, must uss mode 'rb'offset = -8 # initialize offsetwhile -offset < filesize: # offset cannot exceed file sizefp.seek(offset, 2) # read # offset chars from eof(represent by number '2')lines = fp.readlines() # read from fp to eofif len(lines) >= 2: # if contains at least 2 linesreturn lines[-1] # then last line is totally includedelse:offset *= 2 # enlarge offsetfp.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读取文件最后一行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: openresty配置部署
- 下一篇: websocket python爬虫_p