SyntaxFix
Write A Post
Hire A Developer
Questions
Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.
text = re.sub('foobar', 'bar', text)