Merging Files in Blocks with Python

  • Share this:

Code introduction


The function reads two files and merges them in blocks, yielding a merged block each time it is called.


Technology Stack : File reading and writing, generator

Code Type : Generator function

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
        while True:
            block1 = f1.read(1024)
            block2 = f2.read(1024)
            if not block1 and not block2:
                break
            yield block1 + block2