Replace strings in files by Python

前端 未结 5 1178
时光说笑
时光说笑 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 is how I would find and replace strings in files using python. This is a simple little function that will recursively search a directories for a string and replace it with a string. You can also limit files with a certain file extension like the example below.

    import os, fnmatch
    def findReplace(directory, find, replace, filePattern):
        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(filepath) as f:
                    s = f.read()
                s = s.replace(find, replace)
                with open(filepath, "w") as f:
                    f.write(s)
    

    This allows you to do something like:

    findReplace("some_dir", "find this", "replace with this", "*.txt")
    

提交回复
热议问题