Read last lines of file with Python deque
Python collections.deque
is a fast FIFO that does not require thread locking as the more sophisticated queue
.
Use deque
to read the last line of files as follows.
from pathlib import Path
from collections import deque
fn = Path('myfile.txt')
with fn.open('r') as f:
last = deque(f, 1)[0]
last
- last line of file. Throws
IndexError
if file is empty.
By changing 1
the last N lines of the file may be read and indexed.