Reading and Pairing File Chunks

  • Share this:

Code introduction


This function reads data from two files, reading 1024 bytes at a time, and then returning the two-byte chunks as a tuple. If one of the files has reached the end, the read operation stops.


Technology Stack : Built-in libraries (open, read, yield from)

Code Type : File processing

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 and not chunk2:
                break
            yield from [chunk1, chunk2]