如何用 Python 覆盖文件中间的一些字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/508983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:15:54  来源:igfitidea点击:

How to overwrite some bytes in the middle of a file with Python?

pythonfilepatch

提问by sebastien

I'd like to be able to overwrite some bytes at a given offset in a file using Python.

我希望能够使用 Python 在文件中的给定偏移量处覆盖一些字节。

My attempts have failed miserably and resulted in:

我的尝试惨遭失败并导致:

  • overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+")
  • appending the bytes at the end of the file (file mode = "a" or "a+")
  • 覆盖偏移量处的字节,但也在紧随其后截断文件(文件模式 = "w" 或 "w+")
  • 在文件末尾附加字节(文件模式 = "a" 或 "a+")

Is it possible to achieve this with Python in a portable way?

是否有可能以可移植的方式使用 Python 实现这一点?

回答by Ben Blank

Try this:

试试这个:

fh = open("filename.ext", "r+b")
fh.seek(offset)
fh.write(bytes)
fh.close()

回答by tomjen

According to this python pageyou can type file.seek to seek to a particualar offset. You can then write whatever you want.

根据这个 python 页面,您可以输入 file.seek 来寻找特定的偏移量。然后你可以写任何你想要的。

To avoid truncating the file, you can open it with "a+" then seek to the right offset.

为避免截断文件,您可以使用“a+”打开它,然后寻找正确的偏移量。

回答by Johannes Weiss

Very inefficient, but I don't know any other way right now, that doesn't overwritethe bytes in the middle (as Ben Blanks one does):

非常低效,但我现在不知道任何其他方式,这不会覆盖中间的字节(如 Ben Blanks 那样):

a=file('/tmp/test123','r+')
s=a.read()
a.seek(0)
a.write(s[:3]+'xxx'+s[3:])
a.close()

will write 'xxx' at offset 3: 123456789 --> 123xxx456789

将在偏移量 3 处写入 'xxx': 123456789 --> 123xxx456789