Reputation: 13
I need to read two text files and write their alternating lines to a third file. For example:
File1:
A1
A2
File2:
B1
B2
Output file:
A1
B1
A2
B2
Upvotes: 1
Views: 1684
Reputation: 64318
from itertools import zip_longest
with open(filename1) as f1, open(filename2) as f2, open(outfilename, 'w') as of:
for lines in zip_longest(f1, f2):
for line in lines:
if line is not None: print(line, file=of, end='')
EDIT: to fix the problem in cases where the input files don't end with a newline, you change the print
line to this:
print(line.rstrip(), file=of)
Upvotes: 3
Reputation: 23223
Since files are iterables, they can be zip
ed together. Since we want to support a case where number of lines in both input files does not match, we use zip_longest
instead of built-in zip
. This approach does not require loading whole file to memory, so it can be used to merge even a very big files without getting a MemoryError
.
import itertools
with open('file1.txt') as src1, open('file2.txt', 'r') as src2, open('output.txt', 'w') as dst:
for line_from_first, line_from_second in itertools.zip_longest(src1, src2):
if line_from_first is not None:
dst.write(line_from_first)
if line_from_second is not None:
dst.write(line_from_second)
Upvotes: 0