如何编写脚本从Data.yaml读取参数,实现目录创建与文件整理?
问题需求
我在/data/unorganised_texts/目录下有多个子目录(例如/data/unorganised_texts/a-long-story),每个子目录中包含多个文件,核心文件为Data.yaml,示例内容如下:
Category: Name: Space Author: Jôëlle Frankschiff References: Title: Historical Title: Future Title: A “long” story!
需要从Data.yaml中提取:
Category.Name作为$categoryAuthor作为$authorTitle作为$title
创建目录结构:
/data/organised_texts/$category/$author/$title
并将对应子目录下的所有文件复制到该目录中。此前尝试的Bash脚本存在多处问题,希望用Python实现正确方案。
Python实现方案
第一步:安装依赖
首先安装PyYAML库用于解析YAML文件:
pip install pyyaml
第二步:运行脚本
以下是完整的Python脚本,包含容错处理和特殊字符兼容:
import os import shutil import yaml # 定义源目录与目标根目录 SOURCE_ROOT = "/data/unorganised_texts" TARGET_ROOT = "/data/organised_texts" # 遍历源目录下的所有子目录 for subdir_name in os.listdir(SOURCE_ROOT): subdir_path = os.path.join(SOURCE_ROOT, subdir_name) # 仅处理目录 if not os.path.isdir(subdir_path): continue yaml_path = os.path.join(subdir_path, "Data.yaml") # 跳过无Data.yaml的目录 if not os.path.exists(yaml_path): print(f"跳过目录 {subdir_path}:未找到Data.yaml") continue # 解析YAML文件 try: with open(yaml_path, 'r', encoding='utf-8') as f: data = yaml.safe_load(f) except Exception as e: print(f"解析 {yaml_path} 失败:{str(e)}") continue # 提取字段,处理缺失情况 category = data.get("Category", {}).get("Name") author = data.get("Author") title = data.get("Title") # 检查必要字段是否完整 if not all([category, author, title]): print(f"跳过目录 {subdir_path}:缺失Category.Name/Author/Title字段") continue # 处理标题中的特殊字符,避免目录创建失败 safe_title = title.replace("/", "_").replace("\\", "_").replace('"', "").replace("'", "") # 构建目标目录路径 target_dir = os.path.join(TARGET_ROOT, category, author, safe_title) # 递归创建目标目录 try: os.makedirs(target_dir, exist_ok=True) except Exception as e: print(f"创建目录 {target_dir} 失败:{str(e)}") continue # 复制子目录下的所有内容 for item in os.listdir(subdir_path): item_path = os.path.join(subdir_path, item) if os.path.isfile(item_path): try: shutil.copy2(item_path, target_dir) print(f"已复制 {item_path} → {target_dir}") except Exception as e: print(f"复制 {item_path} 失败:{str(e)}") elif os.path.isdir(item_path): # 可选:递归复制子目录,不需要可删除此块 try: dest_subdir = os.path.join(target_dir, item) shutil.copytree(item_path, dest_subdir, dirs_exist_ok=True) print(f"已复制目录 {item_path} → {dest_subdir}") except Exception as e: print(f"复制目录 {item_path} 失败:{str(e)}") print("文件整理完成")
脚本说明
- YAML解析:用PyYAML处理嵌套结构,确保正确提取
Category.Name - 容错机制:跳过无
Data.yaml、字段缺失的目录,捕获文件操作异常 - 特殊字符处理:替换标题中的斜杠、引号等非法字符,避免目录创建失败
- 编码兼容:以UTF-8编码读取YAML,支持带特殊字符的作者名和标题
- 完整复制:支持复制文件和子目录,可根据需求调整是否复制子目录
内容的提问来源于stack exchange,提问作者jakethedog
相关产品推荐
相关产品推荐

