Alternating File Content Merger

  • Share this:

Code introduction


Merge the contents of two files alternately into a new file.


Technology Stack : File operations (built-in)

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2, output):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2, open(output, '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)