Replace and overwrite instead of appending

StackOverflow

I have the following code:

import re
#open the xml file for reading:
file = open("path/test.xml","r+")
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(s+)<string>(.*)</string>",r"<xyz>ABC</xyz>1<xyz>2</xyz>",data))
file.close()

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

file="path/test.xml" 
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