codycrossley
codycrossley

Reputation: 611

Reading Between Specific Lines in Python

I have a text file of the following format:

...text
LINE A
text
text
text
LINE B
text...

What I am trying to do is only work with the text between LINE A and LINE B.

Essentially, I'm trying the following format:

for line in text_file:
     if line.startswith("LINE A"):
          Do something until LINE B

I don't care about what line number it is on because LINE A can be arbitrarily placed in the text file, and the text between LINE A and LINE B is of variable length.

Any tips or pointers would be great!

Thanks!

Upvotes: 1

Views: 113

Answers (1)

Dakkaron
Dakkaron

Reputation: 6276

Use a state machine. In this case I use the states reading and not reading. Since there are only two states I can use one boolean to switch the states.

reading=False
for line in text_file:
    if line.startswith("LINE A"):
        reading=True
    elif line.startswith("LINE B"):
        reading=False
    elif reading:
        Do something

Upvotes: 3

Related Questions