Read and overwrite a file in Python


Currently I’m using this:

f = open(filename, 'r+')
text =
text = re.sub('foobar', 'bar', text)

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.

Asked By: compie



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.

Answered By: Il-Bhima

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 FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")
Answered By: ghostdog74

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

f = open(filename, 'r+')
text =
text = re.sub('foobar', 'bar', text)

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 =
    text = re.sub('foobar', 'bar', text)
Answered By: nosklo

Try writing it in a new file..

f = open(filename, 'r+')
f2= open(filename2,'a+')
text =
text = re.sub('foobar', 'bar', text)
Answered By: sk7979

Honestly you can take a look at this class that I built which does basic file operations. The write method overwrites and append keeps old data.

class IO:
    def read(self, filename):
        toRead = open(filename, "rb")

        out =
        return out
    def write(self, filename, data):
        toWrite = open(filename, "wb")

        out = toWrite.write(data)

    def append(self, filename, data):
        append =
        self.write(filename, append+data)
Answered By: CodinGuy

I find it easier to remember to just read it and then write it.

For example:

with open('file') as f:
    data =
with open('file', 'w') as f:
Answered By: Amy Dowling

To anyone who wants to read and overwrite by line, refer to this answer.

filename = input("Enter filename: ")
with open(filename, 'r+') as file:
    lines = file.readlines()
    for line in lines:
        value = int(line)
        file.write(str(value + 1))
Answered By: SKO
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.