2012-03-23 89 views
2

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

但是,我需要输出结果到一个单独的文件夹。

+1

嗯,原文是什么?如果它在开头是'foo bar'... – cha0site 2012-03-23 18:12:44

回答

2

问题在于您的输出文件夹包含在输入搜索模式中,因此在输入文件上进行一次替换,然后再在输出文件上进行替换。

+1

扩展:如果'outputdir'是'“C:\ stuff \ modified”'并且'inputdir'是'“C:\ stuff”',那么您的代码首先访问''C:\ stuff''写入'“C:\ stuff \ modified”',然后访问'“C:\ stuff \ modified”'并写入'“C:\ stuff \ modified”'。 – 2012-03-23 18:21:38

+0

啊......被缩进挡住了。 。谢谢,马克! :) – Keith 2012-03-23 18:22:57

+0

避免这种情况的一种方法是在外部循环下面添加'if outputdir == path:continue'。 – 2012-03-23 18:24:16