如何将多目录下同名image.fits文件批量复制到单目录并添加编号防覆盖?
批量重命名并整理同名FITS文件
需求概述
需要将不同层级目录下的多个image.fits文件统一整理到指定目录,通过添加前缀编号避免文件覆盖。
现有文件结构:
~/Sources/<unknown>/<foldername1>/image.fits ~/Sources/<unknown>/<foldername2>/image.fits ~/Sources/<unknown>/<foldername3>/image.fits ...
期望整理后的目标结构:
~/Sources/<target_folder>/1_image.fits ~/Sources/<target_folder>/2_image.fits ~/Sources/<target_folder>/3_image.fits ...
要求优先使用通配符访问自动生成的文件夹,支持Shell命令、脚本或Python代码实现。
Shell 脚本方案
通过find命令遍历所有目标文件,配合循环自动编号复制/移动:
# 替换为你的目标目录路径 TARGET_DIR=~/Sources/target_folder # 确保目标目录存在,不存在则创建 mkdir -p "$TARGET_DIR" # 初始化编号计数器 count=1 # 遍历所有image.fits文件,按顺序处理 find ~/Sources -type f -name "image.fits" | while read -r file_path; do # 复制文件到目标目录并添加编号前缀 cp "$file_path" "$TARGET_DIR/${count}_image.fits" # 如需移动文件而非复制,将上面的cp替换为mv即可 ((count++)) done
Python 通用方案
通过递归遍历目录查找目标文件,灵活实现复制/移动:
import os import shutil # 配置路径,使用os.path.expanduser处理用户目录符号~ source_root = os.path.expanduser("~/Sources") target_dir = os.path.expanduser("~/Sources/target_folder") # 创建目标目录,已存在则跳过 os.makedirs(target_dir, exist_ok=True) count = 1 # 递归遍历所有子目录 for root, _, files in os.walk(source_root): for file in files: if file == "image.fits": src_full_path = os.path.join(root, file) dest_full_path = os.path.join(target_dir, f"{count}_image.fits") # 复制文件(保留元数据),换成shutil.move即为移动操作 shutil.copy2(src_full_path, dest_full_path) count += 1
最终采用的修正后方案
基于@Kasper的实现优化,修复路径处理与文件判断逻辑:
import os import shutil if __name__ == '__main__': target_dir = os.path.expanduser("~/Sources/out") # 创建目标目录,已存在则不报错 os.makedirs(target_dir, exist_ok=True) source_root = os.path.expanduser("~/Sources/") # 获取一级子目录(对应结构中的<unknown>) child_dirs = next(os.walk(source_root))[1] num = 1 for dir_name in child_dirs: sub_dir_path = os.path.join(source_root, dir_name) # 获取二级子目录(对应结构中的<foldernameX>) child_child_dirs = next(os.walk(sub_dir_path))[1] for ch_dir in child_child_dirs: # 拼接image.fits的完整路径 src_file = os.path.join(sub_dir_path, ch_dir, "image.fits") if os.path.exists(src_file): dest_file = os.path.join(target_dir, f"{num}_image.fits") # 移动文件,如需复制替换为shutil.copy2 shutil.move(src_file, dest_file) num += 1
内容的提问来源于stack exchange,提问作者Eli
相关产品推荐
相关产品推荐

