如何用Python按文件名中的日期创建层级目录并移动对应文件
Python脚本实现方案
直接使用Python标准库即可完成需求,无需安装第三方依赖,完整代码如下:
import re import shutil from pathlib import Path # 配置要处理的文件夹路径,此处默认是脚本所在的当前目录,可自行修改 source_dir = Path('.') # 匹配文件名中MMDDYYYY格式的8位连续日期 date_pattern = re.compile(r'(\d{2})(\d{2})(\d{4})') for file in source_dir.iterdir(): # 只处理文件,跳过文件夹 if not file.is_file(): continue # 匹配文件名中的日期 match_res = date_pattern.search(file.name) if not match_res: # 没有匹配到日期的文件直接跳过 continue # 提取月、日、年 month, day, year = match_res.groups() # 构造目标层级目录 target_dir = source_dir / year / month / day # 创建目录,已存在时不报错 target_dir.mkdir(parents=True, exist_ok=True) # 移动文件到目标目录 shutil.move(str(file), str(target_dir / file.name))
注意事项
- 运行前建议先备份所有待处理文件,避免操作失误导致文件丢失
- 若你的文件日期格式后续有调整,修改
date_pattern的正则规则即可适配 - 脚本会自动跳过文件名中没有对应格式日期的文件,不会产生误操作
内容的提问来源于stack exchange,提问作者pirate
相关产品推荐
相关产品推荐

