python

python hexdump怎样进行比较

小樊
81
2024-12-06 13:34:06
栏目: 编程语言

要在Python中使用hexdump,您可以使用第三方库hexdump

pip install hexdump

接下来,您可以使用以下代码示例来比较两个文件的内容:

import hexdump
import sys

def compare_files(file1, file2):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
        content1 = f1.read()
        content2 = f2.read()

    diff = []
    for line1, line2 in zip(hexdump.hexdump(content1).split('\n'), hexdump.hexdump(content2).split('\n')):
        if line1 != line2:
            diff.append((line1, line2))

    return diff

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python compare_files.py <file1> <file2>")
        sys.exit(1)

    file1 = sys.argv[1]
    file2 = sys.argv[2]

    diff = compare_files(file1, file2)

    if diff:
        print("Files are different:")
        for line1, line2 in diff:
            print(f"{line1} -> {line2}")
    else:
        print("Files are the same.")

将此代码保存为compare_files.py,然后在命令行中运行它,指定要比较的两个文件的路径,如下所示:

python compare_files.py file1.bin file2.bin

这将输出两个文件之间的差异(如果有)。如果没有差异,它将输出“Files are the same.”。

0
看了该问题的人还看了