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

后端 未结 9 2424
小蘑菇
小蘑菇 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:57

    Check out os.walk:

    import os
    replacement = """some
    multi-line string"""
    for dname, dirs, files in os.walk("some_dir"):
        for fname in files:
            fpath = os.path.join(dname, fname)
            with open(fpath) as f:
                s = f.read()
            s = s.replace("{$replace}", replacement)
            with open(fpath, "w") as f:
                f.write(s)
    

    The above solution has flaws, such as the fact that it opens literally every file it finds, or the fact that each file is read entirely into memory (which would be bad if you had a 1GB text file), but it should be a good starting point.

    You also may want to look into the re module if you want to do a more complex find/replace than looking for a specific string.

提交回复
热议问题