Search code examples
pythonbinaryfilesfile-comparison

How to compare two binary files and return a boolean in Python?


I am reading two files f1 and f2 into my Python code and I need to compare them and get the result as a boolean.

def open_file(file_path):
    with open(input_file, "rb") as f:
    file = f.read()
    
return file

I can however compare them using filecmp but this way, I need to specify the file path and not the variable file from the function


Solution

  • from itertools import zip_longest
    
    def compare_binaries(path1, path2):
        with open(path1, 'rb') as f1, open(path2, 'rb') as f2:
            for line1, line2 in zip_longest(f1, f2, fillvalue=None):
                if line1 == line2:
                    continue
                else:
                    return False
            return True