manyatha
manyatha

Reputation: 5

how to merge two files line by line using python

input:

 hai how are you
 a      
 b

input2:

   1
   hello 
   2

output:

hai how areyou
1
a
hello
b
2

I tried with this code

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)

but i didn't get expected results

how can i achieve this using python give me hint

Upvotes: 0

Views: 1147

Answers (1)

Darius
Darius

Reputation: 12142

You can try that:

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

Upvotes: 1

Related Questions