如何将分组后的文件移动至对应日期命名的子目录(Python)
雷达NC文件分组与目录迁移实现
需求说明
现有一批命名包含日期与el值的NC格式雷达数据文件,要求:当el值出现下降时创建新子目录,将对应文件分组存放。已通过Python代码将文件按规则分组至sweeps列表,现需完成将各组文件移动至以组内首个文件的日期字符串(如20220322_170444)命名的子目录的操作。
示例文件列表
files =[ 'cfrad.20220322_170444.122_COW1_v2_s02_el3.40_SUR.nc', 'cfrad.20220322_170456.550_COW1_v2_s03_el4.22_SUR.nc', 'cfrad.20220322_170508.975_COW1_v2_s04_el5.09_SUR.nc', 'cfrad.20220322_170521.397_COW1_v2_s05_el5.99_SUR.nc', 'cfrad.20220322_170533.811_COW1_v2_s06_el0.45_SUR.nc', ...(其余文件省略) ]
测试文件生成代码
用于创建测试用的空文件(实际场景可跳过):
import numpy as np for file in files: np.savetxt(fname=file, X=np.array([1,1]))
已尝试的分组代码
原分组逻辑代码(注:该代码通过字符串切片截取el值的方式存在局限性,建议后续改用正则提取完整数值进行比较):
import numpy as np from datetime import datetime import glob, os, re import shutil sweeps = [] temp = [] for i, file in enumerate(files[:19]): match_str = re.search(r'\d{4}\d{2}\d{2}_\d{2}\d{2}\d{2}', file) res = datetime.strptime(match_str.group(), '%Y%m%d_%H%M%S') print(res.strftime("%Y%m%d_%H%M%S")) el_pos = int(files[i].find('el')) st_pos = files[i][el_pos+1:el_pos+3] el_pos1 = int(files[i+1].find('el')) end_pos = files[i+1][el_pos1+1:el_pos1+3] temp.append(files[i]) print("len(files):",len(files),i) print(st_pos,end_pos) if st_pos>end_pos: print("temp len: ", len(temp)) sweeps.append(temp) temp = [] elif len(files)-i==2: print('entered') sweeps.append(temp)
目录迁移实现代码
基于已生成的sweeps列表,实现文件分组迁移:
import os import shutil import re # 遍历每个文件组 for sweep_group in sweeps: if not sweep_group: continue # 跳过空组 # 从组内首个文件提取日期字符串 first_file = sweep_group[0] date_match = re.search(r'(\d{4}\d{2}\d{2}_\d{2}\d{2}\d{2})', first_file) if not date_match: print(f"无法从文件{first_file}中提取日期,跳过该组") continue dir_name = date_match.group(1) # 创建目标目录(不存在则创建) if not os.path.exists(dir_name): os.makedirs(dir_name) # 移动组内所有文件到目标目录 for file_path in sweep_group: try: dest_path = os.path.join(dir_name, os.path.basename(file_path)) shutil.move(file_path, dest_path) print(f"已移动文件: {file_path} -> {dest_path}") except Exception as e: print(f"移动文件{file_path}失败: {str(e)}")
补充说明
- 迁移代码通过正则表达式精准提取文件名中的日期字符串,适配符合
YYYYMMDD_HHMMSS格式的文件名。 - 加入异常处理,避免单个文件移动失败导致整个流程中断。
- 自动跳过空组,避免无效操作。
内容的提问来源于stack exchange,提问作者Wind Circulation
相关产品推荐
相关产品推荐

