Home > Blockchain >  Append the following x bytes to a new file when searching for string in a file
Append the following x bytes to a new file when searching for string in a file

Time:09-06

I have a large file with hex data inside listed as such "0A 04 64 72 BD 03..."

My goal is to search for a specific string in the file "BA 1B 65 01" in example, once the string has been found then it copies the next 20 bytes followed after the search index and appends it to a new file. For my scenario there is going to be multiple instances of "BA 1B 65 01" so it needs to detect each times the value is found in the file and append its following 20 bytes every time.

So far I have only made a basic code that searches for the string in question. How would I proceed to have python print the next 20 bytes following i.

file = open('hexfile', 'r')
read = file.readlines()

modified = []
i = "BA 1B 65 01"

for line in read:
    if i in line:
        print("found")
        #print -> 20bytes after i?

CodePudding user response:

You can iterate over the files looking forward to the next 32 bytes at a time. If those bytes match the bytes you want to match with you can read the next 20 bytes. When the file is completely read, the read function will return an empty string (I think, I tested it with StringIO).

with open('hexfile', 'r') as file:
    modified = []
    i = "BA 1B 65 01"

    while line := file.read(32):  # size of BA 1B 65 01 
        if i in line:
            print("found")
            print(file.read(20))

I haven't tested this code so there may be syntax errors.

  • Related