I am trying to read sections of a file into numpy arrays that have similar start and stop flags for the different sections of the file. At the moment I have found a method
The solution similar to yours would be:
result = []
parse = False
with open("myFile.txt") as f:
for line in f:
if line.startswith('stop flag'):
parse = False
elif line.startswith('start flag'):
parse = True
elif parse:
result.append(line)
else: # not needed, but I like to always add else clause
continue
print result
But you might also use inner loop or itertools.takewhile as other answers suggest. Especially using takewhile should be significantly faster for really big files.