Python批量替换文件文本时出现重复替换问题求助
问题原因
你的output_path(D:\Test\output\)位于input_path(D:\Test\)的子目录下,而os.walk会递归遍历输入目录下的所有子目录,包括刚创建的output目录:
- 第一轮遍历处理
D:\Test\下的3个原始txt文件,将替换后的内容写入output目录; - 紧接着
os.walk进入output子目录,读取里面已经被替换过的文件——此时文件内容里依然包含搜索词This(新文本是This\nAndThat,开头就是This),于是再次执行替换操作,导致This被二次替换,多了一行AndThat。
单个文件处理时不会触发这个问题,因为你直接指定了单个原始文件路径,没有遍历子目录,不会读取到output里的文件。
解决方案
可以通过以下几种方式避免重复替换:
方案1:将输出目录移到输入目录外部
把output_path改成不在input_path范围内的路径,比如:
replace_text_in_multiple_files("D:\\Test\\", "D:\\Test_Output\\")
这样os.walk遍历输入目录时,不会触及输出目录。
方案2:遍历过程中跳过output子目录
在os.walk的循环里,修改dirs列表移除output目录(os.walk会根据dirs里的内容决定后续遍历的子目录):
def replace_text_in_multiple_files(input_path, output_path): search_text = "This" new_text = "This\nAndThat" # 先获取output目录的名称,避免硬编码 output_dir_name = os.path.basename(os.path.normpath(output_path)) shutil.rmtree(output_path) os.mkdir(output_path) for subdir, dirs, files in os.walk(input_path): # 移除output目录,防止遍历进去 if output_dir_name in dirs: dirs.remove(output_dir_name) for file in files: input_file_path = subdir + os.sep + file output_file_path = output_path + os.sep + file if input_file_path.endswith(".txt"): s = pathlib.Path(input_file_path).read_text() s = s.replace(search_text, new_text) with open(output_file_path, "w") as f: f.write(s)
方案3:跳过output目录下的文件处理
在处理文件前,判断当前子目录是否是output目录,如果是则跳过:
def replace_text_in_multiple_files(input_path, output_path): search_text = "This" new_text = "This\nAndThat" shutil.rmtree(output_path) os.mkdir(output_path) for subdir, dirs, files in os.walk(input_path): # 如果当前子目录是output目录,跳过处理 if os.path.abspath(subdir) == os.path.abspath(output_path): continue for file in files: input_file_path = subdir + os.sep + file output_file_path = output_path + os.sep + file if input_file_path.endswith(".txt"): s = pathlib.Path(input_file_path).read_text() s = s.replace(search_text, new_text) with open(output_file_path, "w") as f: f.write(s)
内容的提问来源于stack exchange,提问作者Jeffrey Whitney
相关产品推荐
相关产品推荐

