Search code examples
pythonmergealternate

How to merge two text files with alternating lines?


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

Solution

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