读取 Python 中的二进制文件并通过第三个文件中的非零字节将其写入另一个补丁

Reading binary file in Python and writing it into another patching by nonzero bytes from the third file

在 Python-3.x 中,用另一个非零字节修补二进制文件(创建第三个输出文件)的最佳方法是什么,当然要保持原始字节序列?

只是读出源文件和补丁文件并逐字节写入源文件 不是问题,但是如何逐字节解析它们:

    output = open('File3', 'wb')
    patch = open('File2', "rb").read()
    with open('File1', 'rb') as f:
        bytei = f.read(1)
        while bytei != b"":
            output.write(bytei)
            bytei = f.read(1)

所有文件都小于 50kb,速度不是问题。

如果我没理解错的话,那么下面就是你正在尝试做的事情:

from itertools import zip_longest

with open('File1', 'rb') as f1, \
    open('File2', 'rb') as f2, \
    open('File3', 'wb') as f3:

    output = bytearray()

    for v1, v2 in zip_longest(f1.read(), f2.read()):
        output.append(v2 if v2 else v1)

    f3.write(output)

例如:

File1 01 02 03 04 05 06 07 08 09 0a 00
File2 00 11 00 00 14 00 16

给出:

File3 01 11 03 04 14 06 16 08 09 0a 00