[英]Join each line from two files as one line using python
我正在尝试使用 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()))
一个简洁的版本会是这样的
file1=[y.strip() for y in open("file01").readlines()] # read all lines
file2=["|"+x.strip() for x in open("file02").readlines()] #read all lines but add a "|" at begining of line in file2
mergedfile=zip(file1,file2) #combine lines
merged_file=open("a_new_file","w")
for line in mergedfile:
merged_file.write(line[0]+line[1]+"\n") #combine lines
merged_file.close() #close "a_new_file"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.