This Content is from Stack Overflow. Question asked by Eftal Gezer
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.
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
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()
This Question was asked in StackOverflow by Eftal Gezer and Answered by actuallyatiger It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.