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

批量文件字符串替换与规范化重命名:避免文件名冲突

批量文件名清理 + 文件内容替换解决方案

针对你提到的目录树文件整理需求,我写了一个跨平台的Python脚本,可以一次性完成文件名标准化、重复处理和内容批量替换,完全符合你的要求:

核心功能说明

  • 遍历所有子目录的文件,跳过目录本身只处理文件
  • 文件名处理规则:
    • 把所有空格替换为英文句点 .
    • 移除文件名中所有出现的 SOMENAME(精确匹配,如需忽略大小写可以修改脚本)
    • 自动检测重复文件名,追加数字后缀(如 example.txt → example.1.txt → example.2.txt)直到生成唯一名称
  • 文件内容批量替换:可配置多组替换规则,先处理文件名再替换内容,确保文件路径不会出错

完整脚本代码

import pathlib
from typing import Tuple

# -------------------------- 配置参数 --------------------------
# 要处理的根目录(替换成你的目录路径)
ROOT_DIR = pathlib.Path("/path/to/your/directory")
# 要从文件名中移除的字符串
REMOVE_STR = "SOMENAME"
# 文件内容替换规则:(旧字符串, 新字符串),可添加多组
REPLACE_PAIRS = [
    ("old_target_string", "new_replacement_string"),
    # ("another_old_str", "another_new_str")  # 按需添加更多替换规则
]
# 是否开启 dry run(只打印操作,不实际修改文件)
DRY_RUN = False
# -------------------------------------------------------------

def clean_filename(original_name: str) -> str:
    """清理文件名:替换空格为点,移除指定字符串"""
    # 替换空格为句点
    cleaned = original_name.replace(" ", ".")
    # 移除指定字符串
    cleaned = cleaned.replace(REMOVE_STR, "")
    # 清理连续句点(比如原文件名有多个空格或移除后出现..)
    while ".." in cleaned:
        cleaned = cleaned.replace("..", ".")
    # 移除首尾句点,避免无效文件名
    cleaned = cleaned.strip(".")
    # 极端情况:处理后文件名为空,用原文件名前缀临时命名
    if not cleaned:
        cleaned = original_name.split(".")[0] + ".tmp"
    return cleaned

def get_unique_filename(target_dir: pathlib.Path, new_name: str) -> pathlib.Path:
    """生成唯一文件名,若重复则追加数字后缀"""
    base, ext = pathlib.Path(new_name).stem, pathlib.Path(new_name).suffix
    counter = 1
    candidate = target_dir / new_name
    while candidate.exists():
        candidate = target_dir / f"{base}.{counter}{ext}"
        counter += 1
    return candidate

def replace_in_file(file_path: pathlib.Path):
    """批量替换文件内容"""
    try:
        # 读取文件内容(默认utf-8编码,如需其他编码可修改)
        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()
        # 执行所有替换规则
        for old_str, new_str in REPLACE_PAIRS:
            content = content.replace(old_str, new_str)
        # 写回修改后的内容
        if not DRY_RUN:
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(content)
        print(f"✅ 替换内容: {file_path}")
    except UnicodeDecodeError:
        # 跳过二进制文件(无法用utf-8读取的文件)
        print(f"⚠️ 跳过二进制文件: {file_path}")
    except Exception as e:
        print(f"❌ 处理内容失败 {file_path}: {str(e)}")

def main():
    # 遍历所有文件(包括子目录)
    for original_path in ROOT_DIR.rglob("*"):
        if not original_path.is_file():
            continue  # 跳过目录,只处理文件
        
        # 1. 处理文件名
        original_name = original_path.name
        cleaned_name = clean_filename(original_name)
        if cleaned_name == original_name:
            # 文件名无需修改,直接处理内容
            replace_in_file(original_path)
            continue
        
        # 生成唯一目标路径
        target_path = get_unique_filename(original_path.parent, cleaned_name)
        
        # 执行重命名操作
        if DRY_RUN:
            print(f"🔍 Dry Run 重命名: {original_path} → {target_path}")
        else:
            try:
                original_path.rename(target_path)
                print(f"✅ 重命名: {original_path} → {target_path}")
            except Exception as e:
                print(f"❌ 重命名失败 {original_path}: {str(e)}")
                continue
        
        # 2. 处理文件内容(重命名后使用新路径)
        replace_in_file(target_path)

if __name__ == "__main__":
    main()

使用说明

  1. 配置参数:修改脚本顶部的ROOT_DIR为你的目标目录,REMOVE_STR为要移除的字符串,REPLACE_PAIRS添加内容替换规则
  2. 测试运行:先设置DRY_RUN = True,运行脚本查看所有要执行的操作,确认无误后再改为False执行实际修改
  3. 注意事项:
    • 脚本会自动跳过二进制文件(无法用utf-8读取的),如果需要处理二进制文件,可移除UnicodeDecodeError的捕获逻辑
    • 建议处理前备份重要文件,避免意外
    • 文件名处理后会自动清理连续句点和首尾句点,避免生成无效文件名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:03:12