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"