Lets say I have a text file containing
Section 1
What: random1
When: random2
Why: random3
Where: random4
How: random5
Section 2
What: dog1
When: dog2
Why: dog3
Where: dog4
How: dog5
Section 3
What: me1
When: me2
Why: me3
Where: me4
How: me5
I want to create a function to take the text file and look for two words and copy everything in between and keep collecting data and put it in a new text file.
For example: def my_function(document, start, end):
in the interaction window I would put my_function("testing.txt, "when", "why")
and it should create a new text file containing the data:
when: random2
when: dog2
when: me2
So the function takes all the data between those two words and those two words occur more than once so it would have to keep looking through the file.
A user in a different thread has posted a solution that may help me but I am not sure how to put it in a function and I don't understand the code used.
This is from a different thread, solution by: falsetru
import itertools
with open('data.txt', 'r') as f, open('result.txt', 'w') as fout:
while True:
it = itertools.dropwhile(lambda line: line.strip() != 'Start', f)
if next(it, None) is None: break
fout.writelines(itertools.takewhile(lambda line: line.strip() != 'End', it))