简体   繁体   English

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

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

In Python-3.x which is the best way to patch binary file with nonzero bytes from another (creating third output file), all of course keeping original byte sequence? 在Python-3.x中,这是从另一个字节(非零字节)中修补非零字节的二进制文件(创建第三个输出文件)的最佳方法,当然所有这些都保持原始字节顺序吗?

Just to read out source file and patch file and write source byte-by-byte is not a problem, but how to parse both of them byte-by-byte: 仅读取源文件和补丁文件并逐字节写入源文件不是问题,但是如何逐字节解析它们:

    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)

All files are small <50kb, speed isn't issue. 所有文件都小于50kb,速度不成问题。

If I have understood correctly, then the following is what you are attempting to do: 如果我已正确理解,那么您将尝试执行以下操作:

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)

For example: 例如:

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

Gives: 给出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM