5

假设我要处理文件的每一行,但最后一行需要特殊处理:

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() 或类似方法)之外,还有其他解决方案吗?

4

2 回答 2

14

处理一行:

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)
于 2013-08-26T17:32:35.997 回答
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)
于 2013-08-26T17:37:35.273 回答