Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Read a file until a line matches a string in binary mode

Ok, so i have seen the other questions but i run into a unique issue. I have to open the file in binary mode in order to read it (i don't really understand why, but it works). and I can easily print out the lines of the file no problem. But when I try to find a specific line using re.search, I have issues because I have a string pattern and byte objects. Here is what I have so far:

input_file = open(input_file_path,  'rb',  0)

for line in input_file:
    if re.search("enum " + enum_name,  line, 0):
        print("Found it")
        print(line)
        exit()

enum_name is a user input so I really need to know how I can use both a string and the variable in my search of a file opened in binary mode (or how to open this file not in binary mode, I get the can't have unbuffered text I/O error when not in binary mode). I have tried making my pattern for the search binary but I don't know what to do with the variable when I do that.

like image 241
ageoff Avatar asked Oct 07 '22 04:10

ageoff


1 Answers

You need to use a byte string as the pattern in your regex, something like the following should work:

if re.search(b"enum " + enum_name.encode('utf-8'), line):
    ...

The enum_name.encode('utf-8') here is used to convert the user input to a bytes object, depending on your environment you may need to use a difference encoding.

Note that if your regex is really this simple, then you can probably just use a substring search instead.

like image 72
Andrew Clark Avatar answered Oct 12 '22 11:10

Andrew Clark