0

How can I read a text file one section at a time between two markers. for example;

**<Start>** 
code:2010
<Stop>
<Start>
code:2011
code:2013
**<Stop>**

and have it print out one line at a time:

*code:2010
code:2011
code:2013*

I'm using Python3. I've tried looking at 're' but I think I'm way off base. I'm also on a windows machine and don't believe awk or sed are available to me. Any direction would be welcome. Thank you!

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    I think you're over thinking this. If all the data and markers are on separate lines, just read each line one at a time straight from the file and check the contents. – Kind Stranger Oct 05 '17 at 17:23

2 Answers2

0

Something like this might work for your example, but I honestly haven't tested it:

start = 0
textlist = []
with open('myfile') as f:
    for line in f:
        if '<STOP>' in line.upper():
            start = 0
        elif start:
            textlist.append(line)
        elif '<START>' in line.upper():
            start = 1
print(''.join(textlist))
Kind Stranger
  • 1,736
  • 13
  • 18
0

If it's a text/csv you could do something like the following:

import csv
codes = []
with open('myfile.csv', newline='') as f:
     reader=csv.reader(f)
     for line in reader:
           if "code:" in line:
                codes.append([line])


with open('output.csv', 'w', newline='') as f:
     writer = csv.writer(f)
     writer.writerows(codes)
Chris
  • 15,819
  • 3
  • 24
  • 37