python 替换重复字符_Python搜索和替换是重复替换字符串?

博客讲述了使用Python循环浏览文件夹文件进行搜索和替换操作时遇到的问题。将结果输出到不同文件夹时,替换字符串被应用两次,如将'foo'替换为'foo bar',结果成了'foo bar bar'。若不输出到单独文件夹,搜索替换能正常执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

例如:

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)但是,我需要将结果输出到单独的文件夹。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值