Read and overwrite a file in Python

Each Answer to this Q is separated by one/two green lines.

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.

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)

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

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.

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:

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)

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

Try writing it in a new file..

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

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.