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

sebastien picture sebastien · Feb 3, 2009 · Viewed 20.7k times · Source

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:

  • 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+")

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

Answer

Ben Blank picture Ben Blank · Feb 3, 2009

Try this:

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