views:

518

answers:

3

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 :
- either in overwriting the bytes at given offset but also truncating the file just after (file mode = "w" or "w+")
- or in appending the bytes at the end of the file (file mode = "a" or "a+")

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

TIA for your answers.

+2  A: 

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.

tomjen
nice. Good to know stuff.
J.J.
Will test it ASAP, thks
sebastien
No, the answer is opening with "r+b" (binary since we want to overwrite bytes). A "man 3 fopen", section DESCRIPTION should explain the difference among the available modes.
ΤΖΩΤΖΙΟΥ
+9  A: 

Try this:

fh = open("filename.ext", "r+b")
fh.seek(offset)
fh.write(bytes)
fh.close()
Ben Blank
I confirm that this seems to work (but not necessarily with other file modes than r+)
Kena
Will test it ASAP, thks
sebastien
@Kena — The "r+" mode specifically means to open the file for (reading and) writing, leave the "pointer" at the beginning of the file, and do not truncate. The "a+" mode should also work for this, as we use seek anyway, but other modes won't.
Ben Blank
@Ben Blank: "r+" (better, "r+b") is the answer to this. "a+" would NOT work for this. Whatever the seek, a file opened with "a" or "a+" appends any writes at its end.
ΤΖΩΤΖΙΟΥ
@ΤΖΩΤΖΙΟΥ — *checks my notes* D'oh. Right you are. :-)
Ben Blank
r+ did the trick for me.Thank you all !
sebastien
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

Johannes Weiß
Since the OP asked how to overwrite bytes, I think that overwriting the bytes is not actually a problem.
John Fouhy
Sure?quote: My attempts have failed miserably and resulted [...] either in overwriting the bytes at given offset [...]
Johannes Weiß
@Johannes Weiß — You cut that quote off right before the good part. He's lamenting the truncation, not the overwrite.
Ben Blank