我希望以下内容用二进制字符串\x01\x02\x03
替换文件test.bin
中的二进制字符串\x04\x05\x06
。当我运行脚本时,它运行没有错误。但是,当我运行cmp -bl test.bin test.bin.old
(其中test.bin.old
是原始文件的未修改副本)时,我什么也得不到(即test.bin
未被修改)。请问有什么不对?
#!/usr/bin/python
import mmap
filename = "test.bin"
with open(filename, "r+b") as f:
mm = mmap.mmap(f.fileno(), 0, mmap.ACCESS_WRITE)
oldstr = '\x01\x02\x03'
foundpos = mm.find(oldstr)
if foundpos == -1:
print "Could not find string to replace"
exit(-1)
mm.seek(foundpos)
mm.write('\x04\x05\x06')
mm.flush()
mm.close()
f.close()
exit(0)