Replace strings in files by Python

前端 未结 5 1179
时光说笑
时光说笑 2020-12-14 10:26

How can you replace the match with the given replacement recursively in a given directory and its subdirectories?

Pseudo-code

impo         


        
5条回答
  •  春和景丽
    2020-12-14 10:52

    this should work:

    import re, os
    import fnmatch
    for path, dirs, files in os.walk(os.path.abspath(directory)):
           for filename in fnmatch.filter(files, filePattern):
               filepath = os.path.join(path, filename)
               with open("namelist.wps", 'a') as out:
                   with open("namelist.wps", 'r') as readf:
                       for line in readf:
                           line = re.sub(r"dbname=noa user=noa", "dbname=masi user=masi", line)
                           out.write(line)
    

提交回复
热议问题