Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Values between two strings in a text file

Tags:

python

file

csv

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

like image 538
Diao ibrahima Avatar asked Mar 28 '26 00:03

Diao ibrahima


1 Answers

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())
like image 152
Adib Avatar answered Mar 29 '26 13:03

Adib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!