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

如何验证循环处理路径的存在性并避免报错?-DataBricks

解决Databricks中遍历Azure Blob不存在文件夹报错的问题

方法1:提前检查文件夹是否存在

使用Databricks内置的dbutils.fs.exists()方法先验证目标路径是否存在,仅当路径存在时才执行遍历和处理逻辑:

# 替换为你的Azure Blob存储路径
target_folder = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net/target-folder"

if dbutils.fs.exists(target_folder):
    # 遍历文件夹内的文件/子文件夹
    for item in dbutils.fs.ls(target_folder):
        # 写入你的内容处理逻辑
        print(f"Processing: {item.path}")
else:
    print("目标文件夹不存在,无需处理")

方法2:捕获路径不存在的异常

如果不想提前检查,可通过try-except块捕获路径不存在的错误,避免流程中断:

target_folder = "wasbs://<container-name>@<storage-account-name>.blob.core.windows.net/target-folder"

try:
    for item in dbutils.fs.ls(target_folder):
        # 内容处理逻辑
        print(f"Processing: {item.path}")
except Exception as e:
    # 精准匹配路径不存在的错误信息
    if "Path does not exist" in str(e):
        print("目标文件夹不存在,流程正常终止")
    else:
        # 其他异常重新抛出,不屏蔽真实错误
        raise e

注意事项

  • 若使用ADLS Gen2存储,路径格式为abfss://<container-name>@<storage-account-name>.dfs.core.windows.net/<folder-path>,上述两种方法同样适用。
  • 确保Databricks集群已配置好Azure存储的访问权限(如SAS令牌、服务主体等),避免因权限问题导致路径检测失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:03:03