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

Python从input.txt生成奇偶栈并写入文件:for循环异常排查

嘿,我猜你的问题肯定出在行号的计数逻辑上——十有八九是循环里判断奇偶行时,把行号的起始计数搞混了,才导致所有内容都跑到output_even.txt里。我来帮你捋清楚并修正代码:

问题根源分析

Python里用enumerate()遍历文件行时,默认是从0开始计数的。如果你的原代码没指定start=1,那实际的第1行(你想归为奇数行的)对应的索引是0,会被判定为“偶数索引”,直接塞进even栈;第2行索引是1,反而被当成奇数行——完全和你的需求搞反了,最后自然所有内容都进了output_even.txt。

修正后的完整代码

def readTitles():
    # 初始化两个栈
    stack_odd = []
    stack_even = []
    
    # 读取input.txt,用start=1让行号从1开始计数
    with open('input.txt', 'r', encoding='utf-8') as input_file:
        for line_num, line_content in enumerate(input_file, start=1):
            # 去除每行末尾的换行符,避免写入时出现多余空行
            cleaned_line = line_content.rstrip('\n')
            # 按实际行号判断奇偶
            if line_num % 2 == 1:
                stack_odd.append(cleaned_line)
            else:
                stack_even.append(cleaned_line)
    
    # 写入奇数行文件
    with open('output_odd.txt', 'w', encoding='utf-8') as odd_file:
        odd_file.write('\n'.join(stack_odd))
    
    # 写入偶数行文件
    with open('output_even.txt', 'w', encoding='utf-8') as even_file:
        even_file.write('\n'.join(stack_even))

# 调用函数执行
readTitles()

额外注意事项

  1. 用with语句打开文件:它会自动帮你关闭文件,避免资源泄漏;
  2. 处理换行符:用rstrip('\n')只去掉末尾的换行,保留行内的空格;如果需要完全去除首尾空白,可以用strip();
  3. 跳过空行(可选):如果input.txt里有空白行不想计入,可以在加入栈前加个判断:
    if cleaned_line:  # 只有非空行才加入栈
        if line_num % 2 == 1:
            stack_odd.append(cleaned_line)
        else:
            stack_even.append(cleaned_line)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:49:54