Python: reading a file until a string matches a string in binary mode

Ok, so I saw other questions, but I ran into a unique problem. I need to open the file in binary mode in order to read it (I do not understand why, but it works). and I can easily print the lines of the file without any problems. But when I try to find a specific string using re.search , I have problems because I have a string pattern and byte objects. Here is what I still have:

 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 user input, so I really need to know how I can use both a string and a variable in my search for a file opened in binary mode (or how to open this file not in binary mode, I get a jar 't have an unbuffered error text input / output, if not in binary mode). I tried to make my template for binary search, but I do not know what to do with the variable when I do this.

+4
source share
2 answers

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

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

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

Note that if your regular expression is really that simple, you can just use substring search.

+3
source

You do not need to reapply. Try

 if "enum " + enum_name in line: 

Reading with 'b' is mainly related to line endings.

+1
source

All Articles