我有以下代码循环浏览文件夹中的文件并进行简单的搜索和替换,然后将结果输出到其他文件夹。我注意到的是替换字符串似乎被应用了两次。
例如:
Search string: foo
Replace string: foo bar
Result: foo bar bar
这是我的代码。我确定这个问题很明显,但我不能把手指放在上面。
def SearchReplace(directory, search, 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)
outfile = os.path.join(outputdir, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(search, replace)
with open(outfile, "w") as f:
f.write(s)
SearchReplace(inputdir, searchstr, replacestr, ext)
注意:如果我不将结果输出到单独的文件夹,则搜索/替换将按预期执行。意思是,下面的代码工作正常(修改同一文件夹中的输入文件):
def SearchReplace(directory, search, 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(search, replace)
with open(filepath, "w") as f:
f.write(s)
SearchReplace(inputdir, searchstr, replacestr, ext)
但是,我需要将结果输出到单独的文件夹中。
答案 0 :(得分:2)
问题是您的输出文件夹包含在输入搜索模式中,因此替换输入文件一次,然后再输出文件。