Search code examples
pythonpython-3.xfilebinaryfiles

Binary text isn't found in a binary file


I opened a file in binary mode. I need to find a certain string inside this file and print the line after that. However, the string doesn't appear to be found in the text file. I looked into the text file manually, and the string is definitely found on one line.

I tried opening the file as textfile (not binary mode) and not making the string binary, but that gave an error that I solved with this question. The answer on that question led to the below (and current) code.

with open(os.path.join(directory, filename), 'rb') as read_obj:
    # print(read_obj.read())
    for line in read_obj:
        line_number += 1
        if b"PREPARED FOR" in line:
            break
        print(line_number)

Solution

  • Ok. So. Apparently .readlines() worked. I just had to read all the lines, loop through them. Find the one that had the string in it, call that index and add one to find the next line.