views:

98

answers:

2

I have a file opened in 'ab+' mode.

What I need to do is replacing some bytes in the file with another string's bytes such that:

FILE:

thisissomethingasperfectlygood.

string:

01234

So, for example, I seek for the position (4, 0) and I want to write 01234 in the place of "issom" in the file. Last appearance would be:

this01234ethingasperfectlygood.

There are some solutions on the net, but all of them (at least what I could find) are based on "first find a string in the file and then replace it with another one". Because my case is based on seeking, so I am confused about the solution.

+2  A: 

You could mmap() your file and then use slice notation to update specific byte ranges in the file. The example here should help.

sigjuice
Thanks for the info;) I didn't know this library...
israkir
+2  A: 

You can use mmap for that

import os,mmap
f=os.open("afile",os.O_RDWR)
m=mmap.mmap(f,0)
m[4:9]="01234"
os.close(f)
gnibbler
Thanks or the info. One more question; just like i said, I have a opened file in 'ab+' mode. should i open it again with your method along with former one or just open it again closing the other one? I forgot to mention; I am just trying to right a simple server application for my own usage..
israkir
Yeah, you'll have to open it like this. The "a" in the mode seeks to the end of the file before every write, so you can never use that one to write anywhere else in the file
gnibbler
@gnibbler: Actually, you can write anywhere in the file with "ab+" - the "+" means its open for updating, it just happens to start at the tail. mmap does need the OS level file handle however, rather than the python file wrapper object, however you should be able to do this just by passing the result of calling `fileno()` on the file object.ie `f=open('file','a+'); m=mmap.mmap(f.fileno(), 0); ...`
Brian
@Brian: This was what i mean more or less;) Thanks!
israkir