在Databricks中用Python+Spark获取ADLS Gen2最新日期子文件夹问题
ADLS Gen2路径遍历问题排查与解决
问题根源
os.walk是针对本地文件系统的工具,完全不支持ADLS Gen2的abfss://云存储协议路径。它只能识别本地磁盘路径或挂载到本地的文件系统,直接用它遍历abfss路径自然不会有任何输出。
解决方案
在Databricks环境下,推荐使用以下两种原生工具来处理云存储路径:
方法1:使用Databricks内置dbutils.fs(最简便)
dbutils.fs是Databricks专门为云存储设计的文件操作工具,完美支持abfss路径。以下是获取最新日期文件夹的示例代码:
# 替换为你的ADLS Gen2根路径 root_path = "abfss://container@storageaccount.dfs.core.windows.net/Source" # 逐层遍历年/月/日文件夹并筛选最新层级 # 获取年份文件夹并取最新 year_folders = [f.name.strip('/') for f in dbutils.fs.ls(root_path) if f.isDir()] latest_year = sorted(year_folders, reverse=True)[0] # 获取对应年份下的月份文件夹并取最新 month_folders = [f.name.strip('/') for f in dbutils.fs.ls(f"{root_path}/{latest_year}") if f.isDir()] latest_month = sorted(month_folders, reverse=True)[0] # 获取对应月份下的日期文件夹并取最新 day_folders = [f.name.strip('/') for f in dbutils.fs.ls(f"{root_path}/{latest_year}/{latest_month}") if f.isDir()] latest_day = sorted(day_folders, reverse=True)[0] latest_date_folder = f"{latest_year}/{latest_month}/{latest_day}" print(f"最新日期文件夹:{latest_date_folder}")
方法2:使用PySpark文件系统API(适合结合Spark作业)
如果需要和Spark任务联动,可以直接调用Hadoop文件系统API来遍历路径:
from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() hadoop_conf = spark.sparkContext._jsc.hadoopConfiguration() # 初始化文件系统对象 root_path_obj = spark.sparkContext._jvm.org.apache.hadoop.fs.Path(root_path) fs = root_path_obj.getFileSystem(hadoop_conf) # 递归遍历所有日期层级文件夹 def collect_date_folders(path): date_folders = [] for status in fs.listStatus(path): if status.isDirectory(): sub_path_str = status.getPath().toString() # 判断是否到达日层级(路径深度匹配年/月/日) if len(sub_path_str.split('/')) - len(root_path.split('/')) == 3: date_folders.append(sub_path_str.replace(root_path + '/', '').strip('/')) else: date_folders.extend(collect_date_folders(status.getPath())) return date_folders all_date_folders = collect_date_folders(root_path_obj) latest_date_folder = sorted(all_date_folders, reverse=True)[0] print(f"最新日期文件夹:{latest_date_folder}")
注意事项
- 确保Databricks集群已配置ADLS Gen2的访问权限(服务主体、SAS令牌或托管身份均可),否则即使路径正确也无法读取内容。
- 检查
abfss路径格式是否正确:abfss://<容器名>@<存储账户名>.dfs.core.windows.net/<根路径>
内容的提问来源于stack exchange,提问作者CMJ
相关产品推荐
相关产品推荐

