如何用Python将两个文本文件的行全组合拼接并写入新文件?
Python实现两个文本文件行的全组合拼接
问题说明
现有两个文本文件内容如下:
| file 1 | file 2 |
|---|---|
| zzzzzz | bbbbbb |
| aaaaaa | ffffff |
| nnnnnn | kkkkkk |
需要生成所有行的全组合拼接结果,输出格式如下:
| result | | zzzzzzbbbbbb | | zzzzzzffffff | | zzzzzzkkkkkk | | aaaaaabbbbbb | | aaaaaaffffff | | aaaaaakkkkkk | | nnnnnnbbbbbb | | nnnnnnffffff | | nnnnnnkkkkkk |
现有代码问题
你当前的代码是按行对应拼接(file1第1行+file2第1行,file1第2行+file2第2行),而不是生成所有可能的两两组合,所以无法得到期望的全笛卡尔积结果。
正确解决方案
方式1:嵌套循环实现
用with语句自动管理文件读写,避免手动关闭文件的繁琐:
def write_full_combinations(file1_path, file2_path, output_path): # 读取第一个文件的所有行,仅去除换行符 with open(file1_path, 'r', encoding='utf-8') as f1: lines1 = [line.rstrip('\n') for line in f1] # 读取第二个文件的所有行,仅去除换行符 with open(file2_path, 'r', encoding='utf-8') as f2: lines2 = [line.rstrip('\n') for line in f2] # 生成所有组合并写入结果文件 with open(output_path, 'w', encoding='utf-8') as out_f: # 写入表头 out_f.write("| result |\n") for line1 in lines1: for line2 in lines2: combined_line = f"| {line1}{line2} |\n" out_f.write(combined_line) # 调用函数生成结果 write_full_combinations("1.txt", "2.txt", "result.txt")
方式2:用itertools.product简化代码
itertools.product可以直接生成两个列表的笛卡尔积,代码更简洁:
import itertools def write_full_combinations(file1_path, file2_path, output_path): with open(file1_path, 'r', encoding='utf-8') as f1: lines1 = [line.rstrip('\n') for line in f1] with open(file2_path, 'r', encoding='utf-8') as f2: lines2 = [line.rstrip('\n') for line in f2] with open(output_path, 'w', encoding='utf-8') as out_f: out_f.write("| result |\n") # 生成所有两两组合并写入 for line1, line2 in itertools.product(lines1, lines2): out_f.write(f"| {line1}{line2} |\n") write_full_combinations("1.txt", "2.txt", "result.txt")
关键说明
- 使用
rstrip('\n')而非rstrip():仅去除换行符,避免意外删除行尾的有效空格 with语句会自动关闭文件,比手动调用close()更安全,防止因代码异常导致文件未关闭- 两种方式均能生成所有可能的行组合,完全匹配你的期望输出
内容的提问来源于stack exchange,提问作者M s
相关产品推荐
相关产品推荐

