简体   繁体   English

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

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

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+") 覆盖偏移处的字节,但紧接在文件之后截断文件(文件模式=“ w”或“ w +”)
  • appending the bytes at the end of the file (file mode = "a" or "a+") 在文件末尾附加字节(文件模式=“ a”或“ a +”)

Is it possible to achieve this with Python in a portable way? 是否可以使用Python以可移植的方式实现这一目标?

Try this: 尝试这个:

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

According to this python page you can type file.seek to seek to a particualar offset. 根据此python页面,您可以键入file.seek寻求特定的偏移量。 You can then write whatever you want. 然后,您可以编写任何内容。

To avoid truncating the file, you can open it with "a+" then seek to the right offset. 为避免文件被截断,您可以使用“ a +”将其打开,然后向右偏移。

Very inefficient, but I don't know any other way right now, that doesn't overwrite the bytes in the middle (as Ben Blanks one does): 效率很低,但是我现在不知道其他任何方法, 它不会覆盖中间的字节(就像本·布兰克一样):

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

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

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