FileInput:只为目录中已经处理过的文件制作备份文件

FileInput: Make backup files only for files in directory that have been worked on

我正在使用 os.walk 遍历目录以搜索特定文件类型。找到文件类型(例如 .txt 或 .xml)后,我想使用此定义将文件中的字符串(我们称之为 old)替换为字典中的字符串(我们称它为 new).

def multipleReplace(text, wordDict):
    for key in wordDict:
        text = text.replace(key, wordDict[key])
    return text

起初,我有这个循环:

myDict = #dictionary with keys(old) and values(new)#
home = #some directory#
for dirpath, dirnames, filenames in os.walk(home):
    for Filename in filenames:
        filename = os.path.join(dirpath, Filename)
        if filename.endswith('.txt') or filename.endswith('.xml'):
                with fileinput.FileInput(filename,inplace=True,backup='.bak') as file:
                    for line in file:
                        print(multipleReplace(line,myDict),end='')

这工作很快,并且会在每个找到 old 字符串的文件中用 new 字符串替换 old 字符串。但是,问题在于我的脚本创建每个文件的 .bak 文件,无论它是否在其中找到 old 字符串。

我想仅为包含 old 字符串的文件创建一个 .bak 文件(仅针对已完成替换的文件)。 我尝试读取所有文件并仅附加那些包含 old 字符串的文件(使用类似 newFiles.append(re.findall('\b'+old+'\b',line)) 的方式我可以仅对这些文件使用 FileInput 方法,但正则表达式查找需要永远。

我认为这里不需要正则表达式。唯一缺少的部分是在创建 .bak 文件之前检查文件是否包含 old 字符串。所以,请尝试以下方法:

def multipleReplace(text, wordDict):
    for key in wordDict.keys(): # the keys are the old strings
        text = text.replace(key, wordDict[key])
    return text

myDict = #dictionary with keys(old) and values(new)#
home = #some directory#
for dirpath, dirnames, filenames in os.walk(home):
    for Filename in filenames:
        filename = os.path.join(dirpath, Filename)
        if filename.endswith('.txt') or filename.endswith('.xml'):
            with open(filename, 'r') as f:
                content = f.read() # open and read file content
            if any([key in content for key in wordDict.keys()]):  # check if old strings are found              
                with fileinput.FileInput(filename,inplace=True,backup='.bak') as file:
                    for line in file:
                        print(multipleReplace(line,myDict), end='')