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

Bengt Richter bokr at
Sat Jan 15 04:55:51 CET 2005

On 14 Jan 2005 15:40:27 -0800, "yaipa" <yaipa at> wrote:

>Bengt, and all,
>Thanks for all the good input.   The problems seems to be that .find()
>is good for text files on Windows, but is not much use when it is
>binary data.  The script is for a Assy Language build tool, so I know
Did you try it? Why shouldn't find work for binary data?? At the end of
this, I showed an example of opening and modding a text file _in binary_.

 >>> s= ''.join(chr(i) for i in xrange(256))
 >>> s
 x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ab
 >>> for i in xrange(256):
 ...     assert i == s.find(chr(i))

I.e., all the finds succeded for all 256 possible bytes. Why wouldn't you think that would work fine
for data from a binary file? Of course, find is case sensitive and fixed, not a regex, so it's
not very flexible. It wouldn't be that hard to expand to a list of old,new pairs as a change spec
though. Of course that would slow it down some.

>the exact seek address  of the binary data that I need to replace, so
>maybe I'll just go that way.  It just seemed a little more general to
>do a search and replace rather than having to type in a seek address.
Except you run the risk of not having a unique search result, unless you
have a really guaranteed unique pattern.
>Of course I could use a Lib function to convert the binary data to
>ascii and back, but seems a little over the top in this case.
I think you misunderstand Python strings. There is no need to "convert" the result
of open(filename, 'rb').read(chunksize). Re-read the example below ;-)
>> If you wanted to change a binary file, you'd use it something like
>(although probably let
>> the default buffer size be at 4096, not 20, which is pretty silly
>other than demoing.
>> At least the input chunks are 512 ;-)
>>  >>> from sreplace import sreplace
>>  >>> fw = open('','wb')
        opens a binary output file

>>  >>> for buf in sreplace(iter(lambda
>f=open('','rb'), ''),'out','OUT',20):
        iter(f, sentinel) is the format above. I creates an iterator that
        keeps calling f() until f()==sentinel, which it doesn't return, and that ends the sequence
        f in this case is lambda f=open(inputfilename) 
        and the sentinel is '' -- which is what is returned at EOF.
        The old thing to find was 'out', to be changed to 'OUT', and the 20 was a silly small
        return chunks size for the sreplace(...) iterator. Alll these chunks were simply passed
>>  ...     fw.write(buf)
>>  ...
>>  >>> fw.close()
        and closing the file explicitly wrapped it up.
>>  >>> ^Z

I just typed that in interactively to demo the file change process with the source itself,  so the diff
could show the changes. I guess I should have made runnable as a binary file updater, rather
than a cute demo using command line text. The files are no worry, but what is the source of your old
and new binary patterns that you want use for find and replace? You can't enter them in unescaped format
on a command line, so you may want to specify them in separate binary files, or you could specify them
as Python strings in a module that could be imported. E.g.,

---< >------
# example of various ways to specify binary bytes in strings
from binascii import unhexlify as hex2chr
old = (
'This is plain text.'
+ ''.join(map(chr,[33,44,55, 0xaa])) + '<<-- arbitrary list of binary bytes specified in numerically if desired'
+ chr(33)+chr(44)+chr(55)+ '<<-- though this is plainer for a short sequence'
+ hex2chr('4142433031320001ff') + r'<<-- should be ABC012\x00\x01\xff'

new = '\x00'*len(old) # replace with zero bytes

BTW: Note: changing binaries can be dangerous! Do so at your own risk!!
And this has not been tested worth a darn, so caveat**n.

---< >------
from sreplace import sreplace
def main(infnam, outfnam, old, new):
    infile = open(infnam, 'rb')
    inseq = iter(lambda:, '')
    outfile = open(outfnam, 'wb')
            for buf in sreplace(inseq, old, new):
    except Exception, e:
        print '%s:%s' %(e.__class__.__name__, e)
if __name__ == '__main__':
    import sys
        oldnew = __import__(sys.argv[3])
        main(sys.argv[1], sys.argv[2], oldnew.old,
    except Exception, e:
        print '%s:%s' %(e.__class__.__name__, e)
        raise SystemExit, """
    Usage: [python] infname outfname oldnewmodulename
        where infname is read in binary, and outfname is written
        in binary, replacing instances of old binary data with new
        specified as python strings named old and new respectively
        in a module named oldnewmodulename (without .py extension).


And, if you know where to seek to, that seems like the best way ;-)

Bengt Richter

More information about the Python-list mailing list