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)