To get the last three lines of a file efficiently, use deque
:
from collections import deque
with open('somefile') as fin:
last3 = deque(fin, 3)
This saves reading the whole file into memory to slice off what you didn't actually want.
To reflect your comment - your complete code would be:
from collections import deque
with open('somefile') as fin, open('outputfile', 'w') as fout:
fout.writelines(deque(fin, 3))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…