Hi there!
I faced something similar, please take a closer look at this thread:
Name of the assigned function and modelI ended up with my own solution, which isn't the best way to handle it, but it worked. I saved everything before the word/whole line I need to change (let's call this BEFORE) and everything after that word/line (AFTER). So at the end, I just make changes, add it to BEFORE string and add to the result AFTER string. I guess 'updating' the whole file instead of the line/word isn't good, but at least it works

There are some other awesome solutions in that thread, take a look!
Best regards!