Python在所有子目录中查找和替换文本

时间:2017-04-11 03:35:54

标签: python automation

我试图查找并替换给定目录的所有子控件中的文本,这是我的代码。

import os

folderLocation = "C:\\Users\\josh\\Desktop\\target\\xml\\"
divider = "\\"

pseudoDictionaryKey = []
pseudoDictionaryValue = []


with open("C:/Users/josh/Desktop/FILENAMES.txt", "r") as fi:
    for line in fi:
        tokens = line.strip().split("-->")
        pseudoDictionaryKey.append(tokens[0])
        pseudoDictionaryValue.append(tokens[1])

for subdir, dirs, files in os.walk(folderLocation):
    for fileIn in files:
        if fileIn in pseudoDictionaryKey:
            os.rename(folderLocation + subdir, folderLocation + pseudoDictionaryValue[pseudoDictionaryKey.index(fileIn)])

for subdir, dirs, files in os.walk(folderLocation):
    for fileIn in files:
        result = ""
        with open(folderLocation + fileIn,"r") as fi:            
            result = fi.read()
            for i, value in enumerate(pseudoDictionaryKey):
                result = result.replace(pseudoDictionaryKey[i],pseudoDictionaryValue[i])
        with open(folderLocation + fileIn,"w") as fo:
            fo.write(result)

它找到并替换了文本,但它不知道如何输入子目录我希望它重命名目录中的每个文件中的文本和子目录,比如打开目录中的每个文件,而不仅仅是在FILENAMES.txt中定义的文件

0 个答案:

没有答案