如何使用Python覆盖文件中间的某些字节? [英] How to overwrite some bytes in the middle of a file with Python?

查看:155
本文介绍了如何使用Python覆盖文件中间的某些字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用Python覆盖文件中给定偏移量的某些字节.

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

我的尝试惨遭失败,结果是:

My attempts have failed miserably and resulted in:

  • 覆盖偏移量的字节,但紧接在文件之后截断文件(文件模式="w"或"w +")
  • 在文件末尾附加字节(文件模式="a"或"a +")

是否可以通过Python以可移植的方式实现这一目标?

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

推荐答案

尝试一下:

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

这篇关于如何使用Python覆盖文件中间的某些字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆