我有以下代碼循環瀏覽文件夾中的文件並進行簡單的搜索和替換,然後將結果輸出到不同的文件夾。我注意到替換字符串似乎被應用了兩次。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