How to search and replace text in a file?

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

    def findReplace(find, replace):
    
        import os 
    
        src = os.path.join(os.getcwd(), os.pardir) 
    
        for path, dirs, files in os.walk(os.path.abspath(src)):
    
            for name in files: 
    
                if name.endswith('.py'): 
    
                    filepath = os.path.join(path, name)
    
                    with open(filepath) as f: 
    
                        s = f.read()
    
                    s = s.replace(find, replace) 
    
                    with open(filepath, "w") as f:
    
                        f.write(s) 
    

提交回复
热议问题