Shuzheng
Shuzheng

Reputation: 13860

How to find a specific byte sequence between two file offsets in a binary file using Python?

How to find a specific byte sequence between two file offsets in a binary file using Python?

I want to open a binary file to search for a specific byte sequence 0x66,0x66,...,0x66 between two file offsets start and end.

My idea is to open the file using rb and then set the file position to start using fseek(). Then for each position in the file, I read 16 bytes and compare them to the sequence above (16 bytes in length).

However, there must be an easier way to do this?

Upvotes: 0

Views: 610

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375634

You didn't say it was a large file, so let's assume it fits easily into memory. fseek to the start position, then read end-start bytes. You'll have a bytestring, then you can use .index to find your sequence:

with open("the_file.bin", "rb") as f:
    f.fseek(start)
    data = f.read(end-start)
where = data.index(b"\x66"*16)

Upvotes: 2

Related Questions