Search code examples
pythonparsingreadfile

Read lines between two markers


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!


Solution

  • 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))