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

如何在Python for循环中获取迭代次数(行号)?

获取Python文件遍历中的行号(针对查找特定单词场景)

嘿,这个问题其实很常见,Python里有个专门的函数能帮你轻松搞定——enumerate()!它可以在遍历文件行的时候,同时返回行号和对应的行内容,完美解决你的需求。

先帮你修正代码里的几个小问题(比如没读取文件行、拼写错误、未保存修改等),再给出完整的解决方案:

核心解决方案:使用enumerate()函数

enumerate()默认会从0开始计数,但我们可以通过start=1参数让行号从1开始,更符合日常的行号习惯。

修改后的完整代码

# 用with语句安全打开文件,自动处理关闭操作
with open('guru99.txt', 'r') as f:
    lines = f.readlines()

action = int(input('Enter number: '))
if action == 1:
    # 遍历行的同时获取行号(start=1让行号从1开始)
    for line_num, line in enumerate(lines, start=1):
        if 'banana' in line:
            print(f"Found 'banana' in Line {line_num}: {line.strip()}")
            print('You already purchased banana! You can change the quantity')
            
            # 拆分行内容,准备修改数量
            line_parts = line.split()
            new_qty = int(input('Enter new quantity: '))
            
            # 假设数量是行中的第二个元素(根据你的文件格式调整索引)
            line_parts[1] = str(new_qty)
            # 重新组合成一行
            updated_line = ' '.join(line_parts) + '\n'
            
            # 更新lines列表里的对应行(注意列表索引从0开始,所以要减1)
            lines[line_num - 1] = updated_line
            print(f"Updated Line {line_num}: {updated_line.strip()}")

# 将修改后的内容写回文件
with open('guru99.txt', 'w') as f:
    f.writelines(lines)

关键部分解释

  • enumerate(lines, start=1):每次循环返回两个值,line_num是当前行的编号(从1开始),line是当前行的内容
  • 找到目标行后,直接用line_num就能输出对应的行号
  • 最后通过writelines()把修改后的内容写回文件,确保修改生效

备选方案:手动维护计数器

如果你不想用enumerate(),也可以手动定义一个计数器变量来追踪行号:

with open('guru99.txt', 'r') as f:
    lines = f.readlines()

action = int(input('Enter number: '))
if action == 1:
    line_num = 0
    for line in lines:
        line_num += 1
        if 'banana' in line:
            print(f"Found 'banana' in Line {line_num}: {line.strip()}")
            # 后续修改逻辑和上面一致

不过enumerate()是更简洁、更符合Python风格的写法,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:03:11