How to extract information between two unique words in a large text file

You can use regular expressions for that.

>>> st = "alpha here is my text bravo"
>>> import re
>>> re.findall(r'alpha(.*?)bravo',st)
[' here is my text ']

My test.txt file

alpha here is my line
yipee
bravo

Now using open to read the file and than applying regular expressions.

>>> f = open('test.txt','r')
>>> data = f.read()
>>> x = re.findall(r'alpha(.*?)bravo',data,re.DOTALL)
>>> x
[' here is my line\nyipee\n']
>>> "".join(x).replace('\n',' ')
' here is my line yipee '
>>>

Leave a Comment