我有以下代码循环浏览文件夹中的文件并进行简单的搜索和替换,然后将结果输出到不同的文件夹。我注意到替换字符串似乎被应用了两次。Python搜索和替换是重复替换字符串?
例如:
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)
但是,我需要输出结果到一个单独的文件夹。
嗯,原文是什么?如果它在开头是'foo bar'... – cha0site 2012-03-23 18:12:44