python讀取檔案最後一行

2021-09-02 05:26:57 字數 1496 閱讀 9487

處理檔案時,乙個常見的需求就是讀取檔案的最後一行。那麼這個需求用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怎麼實現呢?乙個樸素的想法如下 with open a.log r as fp lines fp.readlines last line lines 1 即使不考慮異常處理的問題,這個 也不完美,因為如果檔案很大,lines...

讀取檔案的最後一行

def get last line for small file fname with open fname,r encoding utf 8 as f 開啟檔案 lines f.readlines 讀取所有行 first line lines 0 取第一行 last line lines 1 取最...

C 正確讀取檔案最後一行

使用c ifstream來讀取檔案時,發現在讀到檔案結尾時會多讀一行。測試 如下,include include include intmain void std string oneline while inf.eof false return0 data.txt內容如下,輸出如下,多讀了一行,為...