Binary search

Martin v. Löwis martin at
Wed Jan 15 14:01:23 CET 2003

"Rudy Schockaert" <rudy.schockaert at> writes:

> I'm looking for a function that allows me to do a binary search in a file.
> By binary search I mean searching for a sequence of bytes

If you can accommodate to put the entire file into memory, I recommend
the lines

data = open("filename","rb").read()
position = data.find(binary_substring)

Here, binary_substring is the string object that you search for.

If you cannot read the entire file into memory, I recommend to read
sized chunks (of atleast twice the substring size). I'm not aware of a
cookbook-style implementation of such a search algorithm, so when you
are done, please submit it to the cookbook. Make sure you properly
deal with the case where the substring crosses a block boundary.


More information about the Python-list mailing list