You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在目录及子目录中批量搜索替换文本内容

递归目录批量文本替换问题

多方查找没找到简单解决方案,现有教程要么过于完整要么太冗长,不想啃大段内容。核心需求是:在指定目录的所有文件及嵌套子目录中,批量搜索并替换指定文本。

目前用os.scandir()时,不管传.、os.getcwd()还是空参数,都只能处理父目录里的文件,没法遍历子目录。我的目录里有Python代码文件、普通文本文件,还有多层嵌套的子目录,子目录里又有文件和子目录。现有代码能处理单个选中的文件,但递归遍历子目录的功能一直没调通。

目录结构如下:[目录结构示意图]

现有代码片段:

if(FLAG_Option == 2):
    with os.scandir( ) as directory:  # was   '.' and theDIR, hum
        for item in directory:
            if not item.name.startswith('.') and item.is_file():
                with open(item, mode="r+") as file:
                    data = file.read()
                    # print(data)  # Before text replaced
                    data = data.replace(search_text, replace_text)
                    file.write(data)
                    print(data)  # After text is replaced

                with open(item, mode="w") as file:
                    file.write(data)

解决方案

方案1:基于现有os.scandir()改递归

把处理逻辑封装成函数,遇到子目录时递归调用即可:

import os

def replace_in_dir(target_dir, search_text, replace_text):
    with os.scandir(target_dir) as directory:
        for item in directory:
            if item.name.startswith('.'):
                continue  # 跳过隐藏文件/目录
            if item.is_file():
                # 处理文件
                try:
                    with open(item.path, 'r', encoding='utf-8') as f:
                        data = f.read()
                    if search_text not in data:
                        continue  # 无匹配内容,跳过写操作
                    data = data.replace(search_text, replace_text)
                    with open(item.path, 'w', encoding='utf-8') as f:
                        f.write(data)
                    print(f"已处理文件: {item.path}")
                except Exception as e:
                    print(f"处理文件 {item.path} 出错: {e}")
            elif item.is_dir():
                # 递归处理子目录
                replace_in_dir(item.path, search_text, replace_text)

# 调用示例
if FLAG_Option == 2:
    target_dir = "."  # 替换成你的目标目录路径
    replace_in_dir(target_dir, search_text, replace_text)

方案2:用os.walk()更简洁

os.walk()自带递归遍历目录树的功能,代码更简短:

import os

if FLAG_Option == 2:
    target_dir = "."  # 替换成你的目标目录
    for root, dirs, files in os.walk(target_dir):
        # 过滤隐藏目录
        dirs[:] = [d for d in dirs if not d.startswith('.')]
        for file_name in files:
            if file_name.startswith('.'):
                continue  # 跳过隐藏文件
            file_path = os.path.join(root, file_name)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = f.read()
                if search_text not in data:
                    continue
                data = data.replace(search_text, replace_text)
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(data)
                print(f"已处理文件: {file_path}")
            except Exception as e:
                print(f"处理文件 {file_path} 出错: {e}")

关键优化点

  • 指定编码utf-8,避免不同编码文件读取乱码或报错
  • 跳过隐藏文件/目录,避免误操作系统文件
  • 先检查文件是否包含目标文本,减少不必要的写操作
  • 增加异常捕获,单个文件出错不会中断整个批量处理

内容的提问来源于stack exchange,提问作者headscratch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 16:25:25