1

I'm looking for a generic way to replace string in a file. I have a file (which can be .txt, .bat, .xml) and I want to replace a specific string, e.g. "ABC", by another string, e.g. "EFG"

I've tried this:

def replace_in_file(file):
        s = open(file).read()
        s = s.replace("ABC" ,"EFG")
        f = open(file,'w')
        f.write(s)
        f.close()

I've also tried this:

def replace_in_file(file):
    with fileinput.FileInput(file) as file:
        for line in file:
                line.replace("ABC" , "EFG")

But none of them haven't worked!

I want to automate the process below: instructions

Open file with notepad++
Press ctrl+f
go to replace
and replace "ABC" by "EFG"
Moddasir
  • 1,449
  • 13
  • 33
  • 1
    In your first function, did you close the file after reading it? – Henry Yik Jul 23 '19 at 15:58
  • Hi Joevin, your first function looks correct. But how do you call it? Please *edit your question* to include that part of the code, and explain what happens when "it doesn't work": Do you get an error message? An empty file? What? – alexis Jul 23 '19 at 15:59
  • You forgot to `print(line)` in the second try. – tripleee Jul 23 '19 at 16:01
  • Hi @tripleee it seems to work in the terminal i have the correct change but it dosn't change in the file –  Jul 23 '19 at 16:15
  • Because you didn't pass `inplace=True` either. – tripleee Jul 23 '19 at 16:18

1 Answers1

0

I think in a file you cannot replace directly, so you have to write also. Otherwise the change data will not be there. So you can also create a temp file and write over there or you can change the original file. So your both functions are correct, just add something like..

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ): 
    tempFile.write( line.replace( textToSearch, textToReplace ) )

tempFile.close() 
Moddasir
  • 1,449
  • 13
  • 33