Extract Values between two strings in a text file using python

后端 未结 7 1400
闹比i
闹比i 2020-11-29 08:27

Lets say I have a Text file with the below content

fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk

Now I need to wr

7条回答
  •  失恋的感觉
    2020-11-29 08:59

    Just in case you have multiple "Start"s and "End"s in your text file, this will import all the data together, excluding all the "Start"s and "End"s.

    with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
        copy = False
        for line in infile:
            if line.strip() == "Start":
                copy = True
                continue
            elif line.strip() == "End":
                copy = False
                continue
            elif copy:
                outfile.write(line)
    

提交回复
热议问题