If the problem is missing delimiters in the output, add newfile.write(START_PATTERN) and newfile.write(END_PATTERN) in the corresponding if statements.
newfile.write(START_PATTERN)
newfile.write(END_PATTERN)
P.S. Include output in your question.