Why file.write() is appending in r+ mode in Python?

Question:

Assume I have a file content.txt, with the content Ex nihilo nihil fit. I am willing to replace it with Ex nihilo nihil est. The code is:

with open("content.txt", "r+") as f:
    content = f.read()
    content = content.replace("fit", "est")
    print(content)
    f.write(content)
    f.close()

After that, the content of the file becomes:

Ex nihilo nihil fit
Ex nihilo nihil est

Why? The only thing I need is Ex nihilo nihil est. What is the correct code?

Asked By: Eftal Gezer

||

Answers:

r+ opens the file and puts a pointer at the first byte. When you use f.read() the pointer moves to the end of the file, so when you try to write it starts at the end of the file. To move back to the start (so you can override), use f.seek(0):

with open("text.txt", "r+") as f:
    content = f.read()
    content = content.replace("fit", "est")
    print(content)
    f.seek(0)
    f.truncate(0)
    f.write(content)
    f.close()
Answered By: actuallyatiger

At the moment you are appending the modified content to the file.

What you want is to clear the content first.
You can use seek and truncate for that.

with open("content.txt", "r+") as f:
    content = f.read()
    content = content.replace("fit", "est")
    print(content)
    f.seek(0)  # move to first byte
    f.truncate()  # delete content
    f.write(content)
Answered By: bitflip

Try the code below if you want to replace a string in a .txt file :

with open("content.txt", 'r') as file :
    content = file.read()

content = content.replace('fit', 'est')

with open("content.txt", 'w') as file:
    file.write(content)
Answered By: abokey
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.