finding/replacing a long binary pattern in a .bin file

François Pinard pinard at
Thu Jan 13 11:18:18 EST 2005

[Stephen Thorne]

> On 12 Jan 2005 22:36:54 -0800, yaipa <yaipa at> wrote:
> > What would be the common sense way of finding a binary pattern in
> > a .bin file, say some 200 bytes, and replacing it with an updated
> > pattern of the same length at the same offset?  The file itself
> > isn't so large, maybe 32 kbytes is all and the need for speed is not
> > so great, but the need for accuracy in the search/replacement is
> > very important.

> Okay, given the requirements.

> f = file('mybinfile')
> contents =, newbinstring)
> f.close()
> f = file('mybinfile','w')
> f.write(contents)
> f.close()

> Will do it, and do it accurately. But it will also read the entire
> file into memory.

32Kb is a small file indeed, reading it in memory is not a problem!

People sometimes like writing long Python programs.  Here is about the
same, a bit shorter: :-)

buffer = file('mybinfile', 'rb').read().replace(oldbinstring, newbinstring)
file('mybinfile', 'wb').write(buffer)

François Pinard

More information about the Python-list mailing list