如何用Python批量复制/迁移带数字序号的Fixation文件夹结构
解决方案
以下是针对需求的Python实现方案,分复制和迁移两种场景,代码注释清晰,适合刚接触文件管理的新手:
核心思路
- 遍历
Annotations下的0001-0700四位数字命名文件夹 - 对每个文件夹,定位其中的
Fixation子目录 - 在已存在的
Fixations目录下创建对应数字的子文件夹 - 将
Fixation内的所有文件/子目录复制或迁移到目标位置
代码实现
1. 复制Fixation内容(保留原文件)
import os import shutil # 定义根路径,根据实际路径修改 source_root = "./Annotations" target_root = "./Fixations" # 遍历0001到0700的文件夹 for i in range(1, 701): # 生成四位数字的文件夹名(如0001、0002) folder_name = f"{i:04d}" # 源Fixation路径 source_fixation = os.path.join(source_root, folder_name, "Fixation") # 目标路径(Fixations下的对应数字文件夹) target_folder = os.path.join(target_root, folder_name) # 检查源Fixation目录是否存在 if os.path.exists(source_fixation): # 创建目标文件夹(如果已存在则跳过) os.makedirs(target_folder, exist_ok=True) # 复制整个Fixation目录的内容到目标位置 # dirs_exist_ok=True 允许目标目录已存在(Python 3.8+支持) shutil.copytree(source_fixation, target_folder, dirs_exist_ok=True) print(f"已复制 {folder_name}/Fixation 到 {target_folder}") else: print(f"警告:{source_fixation} 不存在,跳过")
2. 迁移Fixation内容(原文件会被移动)
如果不需要保留原Annotations下的Fixation内容,把上面的shutil.copytree替换为shutil.move即可:
# 替换原copytree行 shutil.move(source_fixation, target_folder) print(f"已迁移 {folder_name}/Fixation 到 {target_folder}")
Maps目录的后续处理
处理Maps的逻辑完全一致,只需修改代码中的目录名称:
- 将
source_fixation改为os.path.join(source_root, folder_name, "Maps") - 将
target_root改为你的Maps目标根目录(比如./Maps)
注意事项
- 确保Python版本在3.8及以上(
copytree的dirs_exist_ok参数是3.8新增的,低版本可以用try-except处理目录已存在的情况) - 修改
source_root和target_root为你实际的文件路径(绝对路径、相对路径都可以) - 运行前建议先测试少量文件夹(比如把
range(1,701)改成range(1,5)),确认逻辑正确再批量执行
内容的提问来源于stack exchange,提问作者Kaniran
相关产品推荐
相关产品推荐

