You can use itertools.takewhile each time you reach the start flag to take until the stop:
from itertools import takewhile
with open("myFile.txt") as f:
array = []
for line in f:
if line.startswith('start flag'):
data = takewhile(lambda x: not x.startswith("stop flag"),f)
# use data and repeat
Or just use an inner loop:
with open("myFile.txt") as f:
array = []
for line in f:
if line.startswith('start flag'):
# beginning of section use first lin
for line in f:
# check for end of section breaking if we find the stop lone
if line.startswith("stop flag"):
break
# else process lines from section
A file object returns its own iterator so the pointer will keep moving as you iterate over f
, when you reach the start flag, start processing a section until you hit the stop. There is no reason to re-open the file at all, just use the sections as you iterate once over the lines of the file. If the start and stop flag lines are considered part of the section make sure to also use those too.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…