How to find line from txt file and print next line after that in python

Can anyone tell me how to find a line or word from a text file and then print the next item.
f = open ("E: Test.txt", "r") if "feel" in f: print ('true')

+3


source to share


1 answer


Regex is probably the best option here. My short test file contained the following: feel different

For python 2.4:

>>> import re
>>> match_pattern = r'(<=?\bfeel\b)\s+\w+\b'
>>> f=open('E:Test.txt','r')
>>> ftext=f.read()
>>> f.close()
>>> [found.strip() for found in re.findall(match_pattern, ftext)]
['different']

      



For python 2.7 onwards:

>>> import re
>>> match_pattern = r'(<=?\bfeel\b)\s+\w+\b'
>>> with open('E:Test.txt','r') as f:
>>>     ftext=f.read()
>>> [found.strip() for found in re.findall(match_pattern, ftext)]
['different']

      

This regular expression looksbehind for the word "feel" and returns any spaces plus the next word. We then remove that space from all returned results.

0


source







All Articles