如何在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
相关产品推荐
相关产品推荐

