How to search and replace text in a file?

前端 未结 15 2211
傲寒
傲寒 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:31

    def word_replace(filename,old,new):
        c=0
        with open(filename,'r+',encoding ='utf-8') as f:
            a=f.read()
            b=a.split()
            for i in range(0,len(b)):
                if b[i]==old:
                    c=c+1
            old=old.center(len(old)+2)
            new=new.center(len(new)+2)
            d=a.replace(old,new,c)
            f.truncate(0)
            f.seek(0)
            f.write(d)
        print('All words have been replaced!!!')
    

提交回复
热议问题