假设我想处理文件的每一行,但最后一行需要特殊处理:
with open('my_file.txt') as f:
for line in f:
if <line is the last line>:
handle_last_line(line)
else:
handle_line(line)
问题是,如何实施?似乎没有用于在Python中检测文件结尾的功能。
是否有另一种解决方案,而不是将行读入列表(使用f.readlines()或类似方法)?
答案 0 :(得分:13)
处理上一个行:
with open('my_file.txt') as f:
line = None
previous = next(f, None)
for line in f:
handle_line(previous)
previous = line
if previous is not None:
handle_last_line(previous)
当循环终止时,您知道最后一行刚刚被读取。
通用版本,让您分别处理N个最后几行,使用collections.deque()
object:
from collections import deque
from itertools import islice
with open('my_file.txt') as f:
prev = deque(islice(f, n), n)
for line in f:
handle_line(prev.popleft())
prev.append(line)
for remaining in prev:
handle_last_line(remaining)
答案 1 :(得分:3)
您可以使用itertools.tee
迭代迭代的两个副本:
next_lines, lines = itertools.tee(file_object)
next(next_lines)
for next_line, line in zip(next_lines, lines):
handle_line(line)
last_line = next(lines, None)
if last_line is not None:
handle_last_line(last_line)