Python 如何在Linux shell中更新二进制文件中间的一个字节?

Python 如何在Linux shell中更新二进制文件中间的一个字节?,python,linux,cmp,Python,Linux,Cmp,当我在两个文件上运行cmp时,我得到一个字节的差异: cmp -l file1.dmp_byte file2.dmp 913462 0 100 如何使用值100更新文件file1.dmp的字节913462 可以使用标准Linux shell工具或Python完成吗?在Python中,可以使用内存映射文件: 我接受了答案,但选择了不同的解决方案 def patch_file(fn, diff): for line in diff.split(os.linesep):

当我在两个文件上运行cmp时,我得到一个字节的差异:

cmp -l file1.dmp_byte file2.dmp
913462  0 100
如何使用值100更新文件file1.dmp的字节913462


可以使用标准Linux shell工具或Python完成吗?

在Python中,可以使用内存映射文件:


我接受了答案,但选择了不同的解决方案

def patch_file(fn, diff):
    for line in diff.split(os.linesep):
        if line:
            addr, to_octal, _ = line.strip().split()
            with open(fn , 'r+b') as f:
                f.seek(int(addr)-1)
                f.write(chr(int (to_octal,8)))

diff="""
     3 157 266
     4 232 276
     5 272 273
     6  16  25
    48  64  57
    58 340   0
    64   1   0
    65 104   0
    66 110   0
   541  61  60
   545  61  60
   552  61  60
   559  61  60
 20508  15   0
 20509 157   0
 20510 230   0
 20526  10   0
 20532  15   0
 20533 225   0
 20534 150   0
913437 226   0
913438  37   0
913454  10   0
913460   1   0
913461 104   0
913462 100   0
"""

patch_file(f3,diff)     
def patch_file(fn, diff):
    for line in diff.split(os.linesep):
        if line:
            addr, to_octal, _ = line.strip().split()
            with open(fn , 'r+b') as f:
                f.seek(int(addr)-1)
                f.write(chr(int (to_octal,8)))

diff="""
     3 157 266
     4 232 276
     5 272 273
     6  16  25
    48  64  57
    58 340   0
    64   1   0
    65 104   0
    66 110   0
   541  61  60
   545  61  60
   552  61  60
   559  61  60
 20508  15   0
 20509 157   0
 20510 230   0
 20526  10   0
 20532  15   0
 20533 225   0
 20534 150   0
913437 226   0
913438  37   0
913454  10   0
913460   1   0
913461 104   0
913462 100   0
"""

patch_file(f3,diff)