为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用二进制文件。覆盖特定字节

如何使用二进制文件。覆盖特定字节

炎炎设计 2021-07-29 16:49:07
我正在用 python 编写程序,并且希望能够写入二进制文件中的特定字节。我试图在 shell 中使用一个包含数字 0 到 15 的小二进制文件来执行此操作,但我不知道如何执行此操作。下面是我刚刚用注释输入到 shell 中的代码,以演示我正在尝试做什么:>>> File=open("TEST","wb") # Opens the file for writing.>>> File.write(bytes(range(16))) # Writes the numbers 0 through 15 to the file.16>>> File.close() # Closes the file.>>> File=open("TEST","rb") # Opens the file for reading, so that we can test that its contents are correct.>>> tuple(File.read()) # Expected output: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)>>> File.close() # Closes the file.>>> File=open("TEST","wb") # Opens the file for writing.>>> File.seek(3) # Moves the pointer to position 3. (Fourth byte.)3>>> File.write(b"\x01") # Writes 1 to the file in its current position.1>>> File.close() # Closes the file.>>> File=open("TEST","rb") # Opens the file for reading, so that we can test that its contents are correct.>>> tuple(File.read()) # Expected output: (0, 1, 2, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)(0, 0, 0, 1)>>> File.close()>>> File=open("TEST","wb") # I will try again using apend mode to overwrite.>>> File.write(bytes(range(16)))16>>> File.close()>>> File=open("TEST","ab") # Append mode.>>> File.seek(3)3>>> File.write(b"\x01")1>>> File.close()>>> File=open("TEST","rb")>>> tuple(File.read()) # Expected output: (0, 1, 2, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1)>>> File.close()我想要的输出如图所示,但"wb"似乎删除了文件中的所有数据,而"ab"不能向后查找。如何在不重写整个文件的情况下实现我想要的输出?
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号