修改Python文件归档代码 基于文件名指定片段实现正确路径匹配与分类
文件自动分类代码修改说明
本次修改针对原代码标识识别精度不足的问题,调整内容如下:
- 替换原有的截断式标识匹配逻辑,完整提取文件名中6位日期段后的全量业务标识,可准确区分
HORN_STA、HORN_STD这类同前缀不同后缀的文件,兼容标识后缀2位/4位的长度差异 - 修正原代码存在的缩进语法错误,保证功能可正常运行
- 兼容所有规则内的文件名格式(含多级点分割的带审批标记的长文件名、无多余前缀的短数据文件)
- 完整保留原有按文件类型、是否含
APPROVED关键词分类到对应子文件夹的规则 - 文件夹层级结构沿用项目内已有的目录配置,无需调整原有目录组织
核心识别逻辑调整
原代码提取文件标识时,会将完整标识HORN_STA按下划线拆分后仅取首段(即仅匹配HORN),导致同前缀的HORN_STD会被误分到同一目录。
修改后将完整保留6位日期段后的全量字符串作为匹配键,示例提取结果如下:
- 对文件名
3D_MR_APPROVED_P_SS_2 ().HORNST_3D_MR_200226HORN_STA.csv,提取的核心标识为HORN_STA - 对文件名
M_200303HORN_STA.ASC,提取的核心标识同为HORN_STA - 对文件名
3D_MR_APPROVED_P_SS_4.LILYN8_3D_MR_210409LILY_RDN.csv,提取的核心标识为LILY_RDN
完整修改后代码
import os import shutil import re #! 从当前工作目录读取目录与文件名称 def read_information(): files = [f for f in os.listdir(os.curdir) if os.path.isfile(f)] dirs = [d for d in os.listdir(os.curdir) if os.path.isdir(d)] return(files, dirs) #! 将文件排序至对应文件夹 def sorti(name_map, subfolder_map, files): for i in files: # 跳过已经被移动的文件 if not os.path.exists(i): continue _new = i.split(".") core_tag = None # 按原逻辑定位核心标识段 if len(_new) == 2: split_parts = re.split('(\d{6})', _new[0]) # 取数字段之后的完整字符串作为核心标识,不再截断 if len(split_parts) >=2: core_tag = split_parts[-1] elif len(_new) ==3: split_parts = re.split('(\d{6})', _new[1]) if len(split_parts) >=2: core_tag = split_parts[-1] # 匹配对应一级目录 if core_tag in name_map: new_dir = name_map[core_tag] else: continue # 按文件类型匹配二级子目录 file_suffix = _new[-1].lower() if file_suffix == "csv": if "APPROVED" in i.upper(): sub_dir = subfolder_map["APPROVED"] else: sub_dir = subfolder_map["KRONOS"] path_old = os.path.join(os.curdir, i) path_new = os.path.join(os.curdir, new_dir, sub_dir, i) change_folder(path_old, path_new) elif file_suffix == "db": sub_dir = subfolder_map["DB"] path_old = os.path.join(os.curdir, i) path_new = os.path.join(os.curdir, new_dir, sub_dir, i) change_folder(path_old, path_new) elif file_suffix == "gsi": sub_dir = subfolder_map["GSI"] path_old = os.path.join(os.curdir, i) path_new = os.path.join(os.curdir, new_dir, sub_dir, i) change_folder(path_old, path_new) elif file_suffix in ["dat", "asc", "txt"]: sub_dir = subfolder_map["DETAILS"] path_old = os.path.join(os.curdir, i) path_new = os.path.join(os.curdir, new_dir, sub_dir, i) change_folder(path_old, path_new) #! 校验文件夹与文件标识的映射关系 def file_info(files, directory): extracted_tags = [] for i in files: _new = i.split(".") core_tag = None # 完整提取核心标识,不再截断 if len(_new) == 2: split_parts = re.split('(\d{6})', _new[0]) if len(split_parts) >=2: core_tag = split_parts[-1] elif len(_new) ==3: split_parts = re.split('(\d{6})', _new[1]) if len(split_parts) >=2: core_tag = split_parts[-1] # 去重收集所有出现的核心标识 if core_tag and core_tag not in extracted_tags: extracted_tags.append(core_tag) tag_dir_map = {} # 建立标识与一级目录的映射关系,支持模糊匹配 for tag in extracted_tags: tag_core = tag.lower().split("_")[0] for dir_name in directory: dir_core = dir_name.lower() if tag_core in dir_core: tag_dir_map[tag] = dir_name break return (tag_dir_map) def associate_dir_name(directory, tag_set): tmp_map = {} for dir_name in directory: for tag in tag_set: if re.findall(str(tag), str(dir_name)): tmp_map[tag] = dir_name return(tmp_map) def change_folder(path_old, path_new): try: os.makedirs(os.path.dirname(path_new), exist_ok=True) shutil.move(path_old, path_new) #移动文件至新路径 except Exception as e: pass return def check_sub_folder(path): sub_map = {} path_name = f"./{path}/" dirs = [d.name for d in os.scandir(path_name) if os.path.isdir(d)] for i in dirs: tmp = i.lower() if "approved" in tmp: sub_map["APPROVED"] = i elif "kronos" in tmp: sub_map["KRONOS"] = i elif "details" in tmp: sub_map["DETAILS"] = i elif "raw" in tmp: if "gsi" in tmp: sub_map["GSI"] = i else: sub_map["DB"] = i return sub_map if __name__ == "__main__": files, directory = read_information() name_map = file_info(files, directory) for path in directory: sub_def = check_sub_folder(path) sorti(name_map, sub_def, files)
运行注意事项
- 代码运行前请确认一级文件夹名称包含对应标识的核心前缀(如
HORN、LILY、MOOR),保证标识与目录的映射关系正常生效 - 代码会自动创建缺失的二级子目录,无需手动提前创建
- 文件移动操作做了异常捕获,不会因路径权限不足、路径不存在等问题中断整体流程
内容的提问来源于stack exchange,提问作者python novice
相关产品推荐
相关产品推荐

