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

时间:2017-05-21 18:05:12

标签: python-2.7

输入:

 hai how are you
 a      
 b

input2:

   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实现这一点给我提示

1 个答案:

答案 0 :(得分:1)

您可以尝试:

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()