The string to be replaced in the file by the given position

I have a file open in "ab +" mode.

What I need to do is replace some of the bytes in the file with the following string of bytes so that:

FILE:

thisissomethingasperfectlygood.

      

line:

01234

      

So, for example, I am looking for position (4, 0) and I want to write 01234 instead of "issom" in the file. Last view:

this01234ethingasperfectlygood

...

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

+2


source to share


2 answers


You can use mmap for this



import os,mmap
f=os.open("afile",os.O_RDWR)
m=mmap.mmap(f,0)
m[4:9]="01234"
os.close(f)

      

+2


source


You can mmap () and then use slice notation to update specific bytes in the file. An example here should help.



+2


source







All Articles