0

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

  • What are the contents in your file? – M S Dec 18 '18 at 19:31
  • 3
    *I can however compare them using filecmp but I need to specify the file path here and not the file which is not helpful for my further process* <- Could you elaborate on what this means? – Srini Dec 18 '18 at 19:32
  • These are binary files.. I am getting these files from another C program which I have created. – Vineeth Bharadwaj Dec 18 '18 at 19:34
  • I don't think anyone fully understood what you need, please be clear. – Pedro Lobito Dec 18 '18 at 19:35
  • Hello Srini, I can use filecmp.cmp(file1_path, file2_path) and get a boolean. But I do not want to specify the path of the files as the files are being fed from a C code. I have created an interface between C and Python and need to compare the binary files generated by C code in Pyhton – Vineeth Bharadwaj Dec 18 '18 at 19:36
  • Where did you get stuck? – Pedro Lobito Dec 18 '18 at 19:37
  • The C code is generating two binary files. I need to compare the two files now. If I save the file I could compare it using filecmp. But I do not want to save the file as it takes up too much of time. – Vineeth Bharadwaj Dec 18 '18 at 19:38
  • Let's just say that I am using the above function to read two binary files. I need to compare them and get a boolean as result. How can I do it, please? – Vineeth Bharadwaj Dec 18 '18 at 19:45
  • When you are comparing something; it's specific. For example, compare A with compare B. So 1) get all files under specific folder 2) compare files that don't share the same name using filecmp – JR ibkr Dec 18 '18 at 20:02
  • BTW there is also dircmp. Check it out if that satisfies your requirement or not. https://docs.python.org/3/library/filecmp.html – JR ibkr Dec 18 '18 at 20:03
  • I am generating hundereds of files a minute and it's not possible to save all of them to a folder and compare it. – Vineeth Bharadwaj Dec 18 '18 at 20:06
  • Often, you have to assemble pieces together and make a good plan. I would first of all define my actual objective. Then I would break it down in little pieces. Tackle one at a time. File comparison was one of those piece. You have code to compare two files. Now see how it would fit in your plausible solution. – JR ibkr Dec 18 '18 at 22:31

1 Answers1

1
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
Kevin S
  • 930
  • 10
  • 19