Windows批量重命名含非法字符文件有五种安全方法:一、用Python正则替换;二、用pathlib+translate高效处理;三、带时间戳备份日志;四、仅扫描不修改的预检;五、用shutil.copy2保留元数据复制。

如果您需要在 Windows 系统中批量重命名文件,但文件名中包含系统禁止使用的字符(如 : " / \ | ? *),则可能导致文件无法创建、保存或同步。以下是多种安全、可逆的处理方法:
一、使用 Python 的 os 和 re 模块替换非法字符
该方法通过正则表达式识别并统一替换 Windows 文件系统禁止的字符,保留原始文件结构,适用于大多数脚本化场景。
1、导入 os 和 re 模块:
import os
import re
2、定义非法字符正则模式及替换规则:
illegal_chars = r'[:"/\\|?*]'
replacement = '_'
立即学习“Python免费学习笔记(深入)”;
3、指定目标目录路径:
target_dir = r"C:\your\folder\path"
4、遍历目录内所有文件,对文件名执行替换并重命名:
for filename in os.listdir(target_dir):
new_name = re.sub(illegal_chars, replacement, filename)
if new_name != filename:
old_path = os.path.join(target_dir, filename)
new_path = os.path.join(target_dir, new_name)
os.rename(old_path, new_path)
二、使用 pathlib 与字符串 translate 方法处理
该方法利用字符串的 translate 表高效映射非法字符,避免正则开销,适合大量小文件处理,且支持预设字符映射策略。
1、导入 pathlib 和 string:
from pathlib import Path
import string
2、构建 Windows 非法字符映射表:
illegal_map = str.maketrans({c: '_' for c in ':"/\\|?*'})
3、设置根路径对象:
root = Path(r"C:\your\folder\path")
4、递归获取所有文件路径:
for file_path in root.rglob('*'):
if file_path.is_file():
5、生成新文件名并执行重命名:
stem = file_path.stem.translate(illegal_map)
suffix = file_path.suffix
new_name = f"{stem}{suffix}"
new_path = file_path.parent / new_name
if new_path != file_path and not new_path.exists():
file_path.rename(new_path)
三、保留原始文件名备份并添加时间戳前缀
该方法在重命名前自动备份原文件名至日志,并为新文件添加唯一标识,确保操作可追溯,强烈建议在生产环境首次运行时启用此方案。
1、导入 datetime 模块用于生成时间戳:
from datetime import datetime
2、创建日志文件记录映射关系:
log_path = Path(r"C:\your\folder\path\rename_log.txt")
with open(log_path, "a", encoding="utf-8") as log:
log.write(f"\n=== Batch rename at {datetime.now()} ===\n")
3、对每个文件执行带日志的重命名:
for file_path in Path(r"C:\your\folder\path").iterdir():
if file_path.is_file():
original_name = file_path.name
cleaned_name = re.sub(r'[:"/\\|?*]', '_', original_name)
4、写入日志并执行重命名:
with open(log_path, "a", encoding="utf-8") as log:
log.write(f"{original_name} → {cleaned_name}\n")
if cleaned_name != original_name:
new_path = file_path.parent / cleaned_name
file_path.rename(new_path)
四、过滤并跳过已含非法字符的文件名(仅校验不修改)
该方法不执行任何重命名操作,仅扫描并输出含非法字符的文件路径,适用于审计或预检查阶段,避免误操作导致数据混乱。
1、定义非法字符集合:
illegal_set = set(':"/\\|?*')
2、指定扫描路径:
scan_dir = Path(r"C:\your\folder\path")
3、遍历所有文件并检查文件名是否含非法字符:
for file_path in scan_dir.rglob('*'):
if file_path.is_file():
name_chars = set(file_path.name)
if name_chars & illegal_set:
4、打印违规文件路径:
print(f"Invalid chars found: {file_path}")
五、使用 shutil.copy2 保留元数据并重命名副本
该方法不直接修改原文件,而是创建合规命名的副本并保留修改时间、访问时间等元数据,适用于需严格保持原始文件状态的场景。
1、导入 shutil 和 os:
import shutil
import os
2、定义非法字符替换函数:
def sanitize_name(name):
return re.sub(r'[:"/\\|?*]', '_', name)
3、设定源目录和副本输出目录:
src_dir = Path(r"C:\your\source\path")
dst_dir = Path(r"C:\your\output\path")
dst_dir.mkdir(exist_ok=True)
4、对每个文件生成合规副本:
for file_path in src_dir.iterdir():
if file_path.is_file():
clean_name = sanitize_name(file_path.name)
dst_file = dst_dir / clean_name
5、复制并保留全部文件属性:
if dst_file != file_path:
shutil.copy2(file_path, dst_file)










