I took example code from here.
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()
But I am not able to figure out how to replace multiple words with respective new words. In this example if I want to find some words like (old_text1,old_text2,old_text3,old_text4)
and replace by its respective new words (new_text1,new_text2,new_text3,new_text4)
.
Thanks in advance!
You can iterate over your check words and toReplace words using zip
and then replace.
Ex:
checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")
for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()
It's easy use re module
import re
s = "old_text1 old_text2"
s1 = re.sub("old_text" , "new_text" , s)
output
'new_text1 new_text2'
re.sub substitute the old text with the new text re.sub doc https://docs.python.org/3.7/library/re.html#re.sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With