How to search and replace text in a file?

前端 未结 15 2209
傲寒
傲寒 2020-11-21 20:29

How do I search and replace text in a file using Python 3?

Here is my code:

import os
import sys
import fileinput

print (\"Text to search for:\")
te         


        
15条回答
  •  醉酒成梦
    2020-11-21 21:06

    My variant, one word at a time on the entire file.

    I read it into memory.

    def replace_word(infile,old_word,new_word):
        if not os.path.isfile(infile):
            print ("Error on replace_word, not a regular file: "+infile)
            sys.exit(1)
    
        f1=open(infile,'r').read()
        f2=open(infile,'w')
        m=f1.replace(old_word,new_word)
        f2.write(m)
    

提交回复
热议问题