I want the following piece of code to replace few strings in a file and save the changes. It is doing the right job but just adding the changed lines to the previous file without replacing it. I just want the file to be overwritten. What's wrong in my code?
import os
import sys
fileToSearch = 'sample.csv'
replace_values = {
'text1' : 'text1_new',
'text2' : 'text2_new',
'text3' : 'text3_new'
}
with open(fileToSearch, 'r+') as tempFile:
for line in tempFile:
for key, val in replace_values.items():
if key in line:
tempFile.write(line.replace(key, key.replace(key, val)))