If you do not want to close and reopen the file to avoid race conditions, you can truncate :
f = open(filename, 'r+') text = f.read() text = re.sub('foobar', 'bar', text) f.seek(0) f.write(text) f.truncate() f.close()
Functionality can also be cleaner and safer using with open as for the mVChr comment, which closes the handler even if an error occurs.
with open(filename, 'r+') as f: text = f.read() text = re.sub('foobar', 'bar', text) f.seek(0) f.write(text) f.truncate()
nosklo Mar 11 '10 at 11:16 2010-03-11 11:16
source share