0

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)))
A K Roy
  • 11
  • 1
  • 1
    This question seems to tackled [here](http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) and [here](http://stackoverflow.com/questions/4778697/how-to-replace-update-text-in-a-file-line-by-line) already. – ImportanceOfBeingErnest Oct 02 '16 at 08:06
  • At the end can't you just rename the temporary file to the file name you are reading? – Marichyasana Oct 02 '16 at 08:52
  • You're reading and writing to the file at the same time which is causing the inconsistency. – kmario23 Oct 02 '16 at 10:52

0 Answers0