I have a text file that I read in with Python and I then determine the line numbers of lines that contain particular keywords. For some reason, I find that I have to open the file each time I search for a different keyword. I've tried using a with statement to keep the file open, but this does not seem to work.
In the example below, I find the line number of the last line in the file as well as the first line that contains the string 'Results'
with open(MyFile,'r') as f:
lastline = sum(1 for line in f)
for num, line in enumerate(f):
if 'Results' in line:
ResultLine=num
break
This successfully does the first operation (determining the last line), but not the latter. If I instead just open the file twice it works:
f=open(MyFile, 'r')
lastline = sum(1 for line in f)
f=open(MyFile, 'r')
for num, line in enumerate(f):
if 'Results' in line:
ResultLine=num
break
Any suggestions as to why I can't keep the file open with my with statement?
Thanks for the help.