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

如何逐行交叉合并两个TXT文件?Python代码报错AttributeError求解

问题解答

错误分析

  • Python版本语法问题:Python 3中迭代器不再拥有next()属性,正确的调用方式是使用内置函数next(迭代器对象),而原代码中的it.next()是Python 2的写法,这是报错的直接原因。
  • 逻辑错误:itertools.cycle(iters)会无限循环迭代两个迭代器,当其中一个迭代器的元素被取完后,继续调用next()会触发StopIteration异常,无法生成你需要的交替配对结果。

修正后的原逻辑代码

先修复语法和逻辑问题,让代码可以正常运行:

import itertools

with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
    # 读取并处理每行内容,过滤空行
    w1 = [line.strip() for line in f1 if line.strip()]
    w2 = [line.strip() for line in f2 if line.strip()]
    
    iters = [iter(w1), iter(w2)]
    result = []
    try:
        while True:
            # 循环取两个迭代器的元素,直到其中一个耗尽
            for it in iters:
                result.append(next(it))
    except StopIteration:
        pass

# 保存结果
with open('result.txt', 'w') as result_file:
    for line in result:
        result_file.write(f"{line}\n")

更优实现方案

因为你的需求是将两个文件的行一一配对,第一个文件的行在前,第二个文件的行缩进后紧跟,用zip()函数可以更简洁地实现,完全不需要itertools.cycle:

with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
    # 配对两个文件的对应行,同时过滤空行
    paired_lines = zip(
        (line.strip() for line in f1 if line.strip()),
        (line.strip() for line in f2 if line.strip())
    )
    
    # 生成目标格式的内容
    result = []
    for line1, line2 in paired_lines:
        result.append(line1)
        # 给第二个文件的行添加缩进
        result.append(f" {line2}")

# 写入结果文件
with open('result.txt', 'w') as result_file:
    result_file.write('\n'.join(result) + '\n')

这个方案的优势:

  • 逻辑更直观,直接对应两行配对的需求
  • 自动处理两个文件行数相同的情况(如果行数不同,zip()会以较短的文件为准截断)
  • 代码更简洁,不需要异常捕获处理迭代器耗尽的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:39:09