This itertools solution is neat. I was previously struck by itertools.groupby, one convenient tool.
But still, I was just messing around if I could do it without itertools. So, here (There is one assumption and one drawback: the file is not huge, and it goes one additional full iteration along the lines, respectively.)
I created a sample file called "try":
hello world happy day bye
after you read the file and enter the lines in the line with the variable names:
lines=open('./try').readlines()
then
print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'happy' in line][0]]
gives the result:
['hello\n', 'world\n', 'happy\n']
and
print [each for each in lines if lines.index(each)<=[lines.index(line) for line in lines if 'day' in line][0]]
gives the result:
['hello\n', 'world\n', 'happy\n', 'day\n']
Thus, you have received the last line - the terminal stop line is also included.
source share