Python如何实现两个wordlist文件按行交替合并为单个文件
Python实现两个词表按行交替合并
核心逻辑是并行逐行读取两个输入词表,按「第一词表行、第二词表对应行」的交替顺序写入目标文件,自动处理换行符避免多余空行。
基础实现(两个词表行数一致场景)
把以下代码保存为.py脚本,和wordlist1.txt、wordlist2.txt放在同一目录运行,执行后会直接生成符合要求的wordlist3.txt:
with open('wordlist1.txt', 'r', encoding='utf-8') as f1, \ open('wordlist2.txt', 'r', encoding='utf-8') as f2, \ open('wordlist3.txt', 'w', encoding='utf-8') as f3: for line1, line2 in zip(f1, f2): f3.write(f"{line1.rstrip('\n')}\n") f3.write(f"{line2.rstrip('\n')}\n")
行数不一致兼容方案
如果两个词表行数不等,需要保留较长文件的剩余内容,引入标准库itertools.zip_longest替换原生zip即可,缺失的对应行会自动跳过:
from itertools import zip_longest with open('wordlist1.txt', 'r', encoding='utf-8') as f1, \ open('wordlist2.txt', 'r', encoding='utf-8') as f2, \ open('wordlist3.txt', 'w', encoding='utf-8') as f3: for line1, line2 in zip_longest(f1, f2, fillvalue=''): content1 = line1.rstrip('\n') content2 = line2.rstrip('\n') if content1: f3.write(f"{content1}\n") if content2: f3.write(f"{content2}\n")
内容的提问来源于stack exchange,提问作者HOH_HOH
相关产品推荐
相关产品推荐

