There is a text file,I want to replace a word with another one via python,
I do it like this:
demo.py
def modify_text():
with open('test.txt', "r+") as f:
read_data = f.read()
f.truncate()
f.write(read_data.replace('apple', 'pear'))
running the function above, it will append the content into test.txt
, the original content still exists, f.truncate()
does not work, I want to remove original content, how can I do it?