Python 2.7 如何使用python逐行合并两个文件

Python 2.7 如何使用python逐行合并两个文件,python-2.7,Python 2.7,输入: hai how are you a b 输入2: 1 hello 2 输出: hai how areyou 1 a hello b 2 我用这个密码试过了 with open('file_1', 'rt') as file1, \ open('file_2') 'rt' as file2, \ open('merged_file', 'wt') as outf: for line in heapq.merge(file1, file2):

输入:

 hai how are you
 a      
 b
输入2:

   1
   hello 
   2
输出:

hai how areyou
1
a
hello
b
2
我用这个密码试过了

with open('file_1', 'rt') as file1, \
 open('file_2') 'rt' as file2, \
 open('merged_file', 'wt') as outf:

for line in heapq.merge(file1, file2):
    outf.write(line)
但我没有得到预期的结果

如何使用python实现这一点给我提示你可以试试:

import itertools

with open('a.txt', 'r') as f1, open('b.txt', 'r') as f2:

    # Merge data:
    w1 = [line.strip() for line in f1]
    w2 = [line.strip() for line in f2]
    iters = [iter(w1), iter(w2)]
    result = list(it.next() for it in itertools.cycle(iters))

    # Save data:
    result_file = open('result.txt', 'w')
    for line in result:
        result_file.write("{}\n".format(line))
    result_file.close()