Skip to main content
 首页 » 编程设计

python之使用python将两个文件中的每一行连接为一行

2024年10月24日9yjmyzz

我正在尝试使用 python 将两个文件的行合并为一个文件。谁能帮我解决这个问题:

文件 1:

abc|123|apple 
 
abc|456|orange 
 
abc|123|grape 
 
abc|123|pineapple 
 
abc|123|mango 

文件 2:

boise 
 
idaho 
 
sydney 
 
tokyo 
 
london 

预期输出文件:

abc|123|apple|boise 
abc|456|orange|idaho 
abc|123|grape|sydney 
abc|123|pineapple|tokyo 
abc|123|mango|london 
 
**Code tried so far:** 
 
    from itertools import izip 
    with open('merged.txt', 'w') as res: 
            with open('input1.txt') as f1: 
                    with open('input2.txt') as f2: 
                            for line1, line2 in zip(f1, f2): 
                                    res.write("{} {}\n".format(line1.rstrip(), line2.rstrip())) 

我是 python 的新手,有没有一种简单的方法可以使用分隔符“|”从两个文件中追加行。提前致谢。

请您参考如下方法:

非常接近,只需将最后一行更改为:

res.write("{0}|{1}\n".format(line1.rstrip(), line2.rstrip()))