Lets say I have a Text file with the below content
fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk
Start
hgjkkl
dfghjjk
fghjjj
Start
Good Evening
Good
End
I wrote the following code:
infile = open('test.txt','r')
outfile= open('testt.txt','w')
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
elif line.strip() == "End":
copy = False
elif copy:
outfile.write(line)
I have this result in outfile:
Good Morning
Hello World
hgjkkl
dfghjjk
fghjjj
Good Evening
Good
My problem is I want to take just the data between start and end but not between start and start or End and End
Great problem! This is a bucket problem where each start needs an end.
The reason why you got the result is because there are two consecutive 'Start'.
It's best to store the information somewhere until 'End' is triggered.
infile = open('scores.txt','r')
outfile= open('testt.txt','w')
copy = False
for line in infile:
if line.strip() == "Start":
bucket = []
copy = True
elif line.strip() == "End":
for strings in bucket:
outfile.write( strings + '\n')
copy = False
elif copy:
bucket.append(line.strip())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With