You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Databricks中通过dbutils根据子目录名提取ADLS Gen2父目录名?

解决方案

核心逻辑是遍历original_data下的所有一级目录,逐个验证是否包含目标子目录,找到后返回对应的父目录名称。以下是基于dbutils.fs的可运行代码:

def find_parent_folders(target_child_folder):
    # 定义ADLS根目录路径
    root_path = "abfss://mycontainer@mystorageaccount.dfs.core.windows.net/original_data/"
    # 获取根目录下的所有一级条目
    root_entries = dbutils.fs.ls(root_path)
    
    matched_parent_dirs = []
    for entry in root_entries:
        # 只处理目录(跳过文件)
        if entry.isDir():
            # 拼接目标子目录的完整路径
            child_dir_path = f"{entry.path}{target_child_folder}/"
            # 检查该子目录是否存在
            if dbutils.fs.exists(child_dir_path):
                # 从路径中提取父目录名称
                parent_dir_name = entry.path.strip("/").split("/")[-1]
                matched_parent_dirs.append(parent_dir_name)
    
    return matched_parent_dirs

# 使用示例:替换为实际的child_folder_main名称
target_child_name = "your_child_folder_main_name"
result = find_parent_folders(target_child_name)

if result:
    print(f"匹配的父目录:{result}")
else:
    print(f"未找到包含子目录'{target_child_name}'的父目录")

关键说明

  • dbutils.fs.ls(root_path):获取original_data下的所有一级目录和文件,通过entry.isDir()过滤出目录项
  • dbutils.fs.exists(child_dir_path):验证当前一级目录下是否存在目标子目录
  • 路径处理:通过strip("/")移除路径首尾的斜杠,再用split("/")拆分路径,取最后一段作为父目录名称
  • 返回结果:支持返回多个匹配的父目录(如果存在多个一级目录包含同名子目录)

内容的提问来源于stack exchange,提问作者LearneR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:52:08