简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM