Generator for Alternating File Reads

  • Share this:

Code introduction


This function merges the reading of two files, reading 1024 bytes each time, alternating between the two files, and returning a generator.


Technology Stack : Built-in file operations

Code Type : File operation

Code Difficulty : Intermediate


                
                    
def zipfiles(file1, file2):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
        while True:
            chunk1 = f1.read(1024)
            chunk2 = f2.read(1024)
            if not chunk1 or not chunk2:
                break
            yield from (chunk1, chunk2)