compie compie - 5 months ago 7
Python Question

Read and overwrite a file in Python

Currently I'm using this:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()


But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.

Answer

If you don't want to close and reopen the file, to avoid race conditions, you could truncate it:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
Comments