Read and overwrite a file in Python Read and overwrite a file in Python python python

Read and overwrite a file in Python


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()

The functionality will likely also be cleaner and safer using open as a context manager, which will close the file 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()


The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.

from fileinput import FileInputfor line in FileInput("file", inplace=1):    line = line.replace("foobar", "bar")    print(line)


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.