Extract Values between two strings in a text file using python

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)

Leave a Comment