在 Python 中读取文件最后几行的方法有多种,以下是其中几种常用的方法:
seek()
函数和
readlines()
函数:首先将文件指针移动到文件末尾,然后读取整个文件。最后取出最后几行。
with open(file_path, 'r') as f:
f.seek(0, 2)
lines = f.readlines()
last_n_lines = lines[-n:]
使用 subprocess 模块的 Popen() 函数和 tail 命令:
import subprocess
with open(file_path, 'r') as f:
output = subprocess.Popen(['tail', '-n', str(n), file_path], stdout=subprocess.PIPE).communicate()[0]
last_n_lines = output.decode().split('\n')
使用 deque 和 readline() 函数:使用双端队列在读取文件时维护最后几行。
from collections import deque
with open(file_path, 'r') as f:
dq = deque(f, n)
last_n_lines = list(dq)
请注意,这些方法的效率和内存使用情况可能有所不同。