Replace and overwrite instead of appending


I have the following code:

import re
#open the xml file for reading:
file = open("path/test.xml","r+")
#convert to string:
data =

where I"d like to replace the old content that"s in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?

Answer rating: 90

with open(file, "w") as filetowrite:
    filetowrite.write("new content")

Open the file in "w" mode, you will be able to replace its current text save the file with new contents.

Get Solution for free from DataCamp guru