1
votes

I have a text file with message where it started with 'START' line and ends with 'END' line. I want the python code to read lines between these two words. I have a code which is reading lines between these two words. but it is also reading 'START' and 'End' lines. i want only lines between these two words.

i have tried this code which is also reading 'START' and 'END' words.

data=[]
flag=False
with open('/tmp/test.txt','r') as f:
    for line in f:
        if line.startswith('START'):
            flag=True
        if flag:
            data.append(line)
        if line.strip().endswith('END'):
            flag=False

print ''.join(data)  

please suggest the code which will read between two words excluding 'START' and 'END' lines

2
A sample of your test.txt? - DirtyBit

2 Answers

1
votes

Just rearrange your if statements. Think about the order in which they flow and when if flag is being evaluated. Also, you can use elif so only one of the three conditions would execute, but make sure the elif flag line is the last condition.

With the way you have your example setup, it will check to see if the line starts with START, and then set the flag. Immediately after that happens, you are checking if the flag was set, so it will print out START. Additionally it will print every line, then check after you've printed the line to see if it should have printed END or not.

With rearranging the order, you will see that if the line starts with START, then there's no command below that will print the line. Similarly, it checks to see if it should stop before printing the END line.

with open('/tmp/test.txt','r') as f:
    for line in f:
        if line.strip().endswith('END'):
            flag=False
        if flag:
            data.append(line)
        if line.startswith('START'):
            flag=True

The elif version is probably the better way to go since it will save you a few checks of if statements, but only one outcome can be executed per iteration. So if a flag is changed, then it will never print out the line.

with open('/tmp/test.txt','r') as f:
    for line in f:
        if line.startswith('START'):
            flag=True
        elif line.strip().endswith('END'):
            flag=False
        elif flag:
            data.append(line)
1
votes

Use elif, rather than multiple ifs, to ensure only one branch is executed.

data=[]
flag=False
with open('/tmp/test.txt','r') as f:
    for line in f:
        if line.startswith('START'):
            flag=True
        elif line.strip().endswith('END'):
            flag=False
        elif flag:
            data.append(line)

print '\n'.join(data)