Merging Two Files Alternately

  • Share this:

Code introduction


This function merges the contents of two files by alternating the content of each file into the output file.


Technology Stack : Built-in library: open

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2, output_file):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2, open(output_file, 'wb') as f_out:
        while True:
            chunk1 = f1.read(1024)
            chunk2 = f2.read(1024)
            if not chunk1 and not chunk2:
                break
            f_out.write(chunk1)
            f_out.write(chunk2)