Python – copy section of text in file python

pythonpython-3.x

I need to extract values from the text file below:

fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk

The values I need to extract are from Start to End.

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
        elif line.strip() == "End":
            copy = False
        elif copy:
            outfile.write(line)

The code above I am using is from this question:
Extract Values between two strings in a text file using python

This code will not include the strings "Start" and "End" just what is inside them. How would you include the perimeter strings?

Best Answer

@en_Knight has it almost right. Here's a fix to meet the OP's request that the delimiters ARE included in the output:

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
        if copy:
            outfile.write(line)
        # move this AFTER the "if copy"
        if line.strip() == "End":
            copy = False

OR simply include the write() in the case it applies to:

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

Update: to answer the question in the comment "only use the 1st occurance of 'End' after 'Start'", change the last elif line.strip() == "End" to:

        elif line.strip() == "End" and copy:
            outfile.write(line) # add this
            copy = False

This works if there is only ONE "Start" but multiple "End" lines... which sounds odd, but that is what the questioner asked.