You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现检测文本文件指定标题后打印其下一行

问题分析与修复方案

原代码无法运行的核心问题:

  • 调用f.readlines()后,文件对象的迭代器已经走到文件末尾,再调用f.next()会触发StopIteration错误
  • 就算没耗尽,文件指针和列表lines的遍历位置完全不同步,无法正确定位到目标行的下一行

修复方案一:基于列表索引处理(适合小文件)

把所有行读入列表后,通过索引定位目标行的下一行,同时做越界检查避免报错:

def openFood():
    with open("FoodList.txt") as f:
        lines = f.readlines()
        for idx, line in enumerate(lines):
            # 去除换行符和空格,避免匹配时受格式干扰
            if 'Food' in line.strip():
                # 确保下一行存在,防止索引越界
                if idx + 1 < len(lines):
                    print(lines[idx + 1].strip())

openFood()

修复方案二:基于文件迭代器的标志位处理(适合大文件)

不需要一次性读取所有行,通过标志位记录是否要打印下一行,内存占用更低:

def openFood():
    with open("FoodList.txt") as f:
        print_next = False
        for line in f:
            cleaned_line = line.strip()
            if print_next:
                print(cleaned_line)
                print_next = False  # 打印后重置标志,避免连续打印
            if 'Food' in cleaned_line:
                print_next = True

openFood()

内容的提问来源于stack exchange,提问作者SohrabFarjami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 02:36:18