我有以下代码循环浏览文件夹中的文件并进行简单的搜索和替换,然后将结果输出到不同的文件夹。我注意到替换字符串似乎被应用了两次。
例如:
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)但是,我需要将结果输出到单独的文件夹。