如何使用目录级SAS令牌列出并下载Azure Data Lake Gen2目录文件
解决Azure Data Lake Gen2特定文件夹SAS令牌下的文件列出与下载问题
核心方案
由于你的SAS令牌仅授权特定子文件夹访问,无法使用FileSystemClient的根级遍历功能,可基于DataLakeDirectoryClient实现递归遍历目录,手动收集所有文件路径后逐个下载。
具体实现步骤
1. 递归遍历目录获取所有文件路径
利用DataLakeDirectoryClient.list_paths()方法(该方法仅需当前目录的SAS权限),编写递归函数遍历所有层级的文件和子目录,收集完整文件路径:
def get_all_files(directory_client): file_paths = [] # 列出当前目录下的所有文件和子目录 paths = directory_client.list_paths() for path in paths: if path.is_file: file_paths.append(path.name) else: # 递归处理子目录 sub_dir_client = directory_client.get_subdirectory_client(path.name) file_paths.extend(get_all_files(sub_dir_client)) return file_paths
2. 单个文件下载函数
编写函数通过文件路径获取DataLakeFileClient,将云端文件下载到本地:
def download_file(directory_client, remote_file_path, local_save_path): file_client = directory_client.get_file_client(remote_file_path) with open(local_save_path, "wb") as local_file: download_stream = file_client.download_file() local_file.write(download_stream.readall())
3. 整合完整流程
结合上述函数,先获取所有文件路径,再按云端目录结构下载到本地:
# 初始化目录客户端(沿用你提供的配置) url = 'https://my-account.blob.core.windows.net' sas_token = '<sas-token>' file_system_name = 'file_system_1' subfolder_path = 'subfolder_1' data_lake_service_client = DataLakeServiceClient(account_url=url, credential=sas_token) data_lake_directory_client = data_lake_service_client.get_directory_client(file_system=file_system_name, directory=subfolder_path) # 获取目标文件夹下所有文件路径 all_files = get_all_files(data_lake_directory_client) # 批量下载并保持本地目录结构 import os local_root = "./downloaded_files" for file_path in all_files: local_file_path = os.path.join(local_root, file_path) # 自动创建不存在的本地目录 os.makedirs(os.path.dirname(local_file_path), exist_ok=True) download_file(data_lake_directory_client, file_path, local_file_path)
关键说明
DataLakeDirectoryClient.list_paths()是核心:该方法无需文件系统级权限,只要当前目录的SAS权限有效,即可列出目录内所有内容。- 递归遍历确保完整性:能覆盖子文件夹层级,不会遗漏深层文件。
- 本地目录结构同步:通过
os.makedirs自动创建对应目录,保证下载后的文件结构与云端一致。
内容的提问来源于stack exchange,提问作者elyptikus
相关产品推荐
相关产品推荐

