Python - Way to recursively find and replace string in text files

后端 未结 9 2407
小蘑菇
小蘑菇 2020-12-24 01:56

I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi l

9条回答
  •  不思量自难忘°
    2020-12-24 02:40

    Here's my code (which I think is the same as the above but I'm including it just in case there's something subtly different about it):

    import os, fnmatch, sys
    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)
    

    it runs without error. BUT, the file, in z:\test is unchanged. I've put in print statements, like print("got here") but they don't print out either.

提交回复
热议问题