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

24,520

Solution 1

Try this:

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

Solution 2

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

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

Share:
24,520
sebastien
Author by

sebastien

Updated on July 09, 2022

Comments

  • sebastien
    sebastien almost 2 years

    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?