Python:替换嵌套折叠的所有文件中的文本

2024-10-01 11:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图替换目录中所有json文件中的一个文本字符串。目录有多个嵌套目录,目录结构的深度不得而知。下面是我的代码,它不替换字符串。你知道吗

import os
import pathlib
import glob
def main():
    replacement =  "New"
    oldTex = "Old"
    baseFolder = '1.5.13_test_2'
    fullPath = "/Users/gfKron/path"

    for item in glob.glob(fullPath +"/*.json", recursive=True):
        temp = []
        with open(item, "r") as f:
            for line in f:
                line.replace(oldTex, replacement)
                temp.append(line)
        with open(item, "w") as f:
            f.writelines(temp)
            f.close()
if __name__== "__main__":
    main()   

非常感谢您的帮助。你知道吗


Tags: 字符串inimport目录jsonformainwith