Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.write(content)
    f.close()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading