我正在尝试使用 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()))
关于python - 使用 python 将两个文件中的每一行连接为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862802/