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



input:

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

最新更新