find and replace multiple words in a file python

后端 未结 5 1872
生来不讨喜
生来不讨喜 2020-12-30 18:54

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         


        
5条回答
  •  天涯浪人
    2020-12-30 19:14

    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()
    

提交回复
热议问题