Reputation: 2019
I have the following code that's looping through files in a folder and doing a simple search and replace, and then outputs the results to a different folder. What I am noticing is that the replace string seems to be getting applied twice.
For example:
Search string: foo
Replace string: foo bar
Result: foo bar bar
Here is my code. I'm sure the problem is obvious, but I just can't put my finger on it.
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)
NOTE: if I do not output the results to a separate folder, the search/replace performs as expected. Meaning, the code below works fine (modifies input file in same folder):
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)
However, I need to output the results to a separate folder.
Upvotes: 2
Views: 269
Reputation: 838156
The problem is that your output folder is included in the input search pattern, so the replacement is made once on the input file, then again on the output file.
Upvotes: 2