python - Python中如何判断一行是否是最后一行?

标签 python

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

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

最佳答案

处理行:

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)

关于python - Python中如何判断一行是否是最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18449646/

相关文章:

python - pandas str.replace - 如果正则表达式在将字符串转换为数字时未能避免 NaN,则保留当前值

Python:在列表中查找项目

python - PyQt 显示来自 opencv 的视频流

python - 删除二进制搜索树python中的节点

python - Python中的1000位pi

python - 如何在 Python 中更新显示的值而不是每次都打印?

python - 使用 pandas 根据行值将列转换为行

python - SQLAlchemy——我可以在 DDL 中将空字符串映射到 null 吗?我想要一个可为空的整数列在插入或更新时将 '' 转换为 NULL

python - 使用 importlib 导入具有本地名称的模块

python - Python 中的深度优先搜索(包括循环)