Python遍历文本文件每次前移1行 同步获取当前行与下一行的方法
问题原因
你原本使用的zip_longest(*[f] * 2)写法本质是将文件迭代器按步长2分组取连续两个元素,得到的组合是(a,b)、(c,d)、(e,None),属于固定窗口非重叠配对,自然无法实现相邻行滑动重叠配对的需求。
实现方案
可根据处理的文件体积选对应方案:
方案1:小文件场景(逻辑最简单)
如果处理的文件体积不大,直接把所有行读入列表后按索引遍历即可,代码可读性最高:
txt_file = "your_file_path.txt" with open(txt_file, "r") as f: lines = [line.rstrip() for line in f] for idx in range(len(lines)): current_line = lines[idx] next_line = lines[idx+1] if idx < len(lines) - 1 else None if next_line is not None: print(current_line + next_line) else: print(current_line)
运行后输出完全匹配预期:
ab bc cd de e
方案2:大文件场景(内存占用极低)
如果需要处理GB级别的大文件,不适合把全量内容读入内存,可以用itertools.tee生成两个偏移的迭代器做滑动配对,全程内存仅保留当前处理的两行内容:
import itertools txt_file = "your_file_path.txt" with open(txt_file, "r") as f: # 生成两个独立的文件内容迭代器 it_curr, it_next = itertools.tee(f) # 指向next行的迭代器向前偏移1位,跳过第一行 next(it_next, None) # 配对遍历,迭代到末尾时自动补None for line_curr, line_next in itertools.zip_longest(it_curr, it_next): res = line_curr.rstrip() if line_next is not None: res += line_next.rstrip() print(res)
注意点
判断空值建议用is None/is not None,不要用== None/!= None,避免自定义对象重载相等判断逻辑导致结果异常。
内容的提问来源于stack exchange,提问作者hongdekong
相关产品推荐
相关产品推荐

