【问题标题】:How to compare two binary files and return a boolean in Python?如何比较两个二进制文件并在 Python 中返回布尔值?
【发布时间】:2018-12-18 19:30:34
【问题描述】:

我正在将两个文件 f1 和 f2 读入我的 Python 代码中,我需要比较它们并将结果作为布尔值。

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

但是我可以使用filecmp 比较它们,但是这样,我需要从函数中指定文件路径而不是变量file

【问题讨论】:

  • 你的文件内容是什么?
  • 我可以使用 filecmp 比较它们,但我需要在这里指定文件路径,而不是对我的进一步处理没有帮助的文件
  • 这些是二进制文件。我正在从我创建的另一个 C 程序中获取这些文件。
  • 我认为没有人完全理解您的需求,请清楚。
  • 你好 Srini,我可以使用 filecmp.cmp(file1_path, file2_path) 并获得一个布尔值。但是我不想指定文件的路径,因为这些文件是从 C 代码提供的。我已经创建了 C 和 Python 之间的接口,需要在 Pyhton 中比较 C 代码生成的二进制文件

标签: python binaryfiles file-comparison


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多