如何使用Azure Python SDK从Azure注册表下载数据资产文件
使用Azure Python SDK下载注册表中数据资产容器的所有文件
步骤1:安装所需SDK包
先确保安装Azure ML和Storage Blob的Python SDK:
pip install azure-ai-ml azure-storage-blob python-dotenv
步骤2:初始化MLClient并获取目标数据资产
通过MLClient连接Azure ML注册表,再获取名为train的数据资产:
from azure.ai.ml import MLClient from azure.identity import DefaultAzureCredential from azure.storage.blob import BlobServiceClient, ContainerClient import os # 替换为你的Azure资源信息 ml_client = MLClient( credential=DefaultAzureCredential(), registry_name="你的注册表名称", subscription_id="你的订阅ID", resource_group_name="你的资源组名称" ) # 获取数据资产,可指定版本(若存在多版本) data_asset = ml_client.data.get(name="train", version="1") # 替换为实际版本号
步骤3:解析数据资产的存储信息
从数据资产中提取存储账户、容器名和文件前缀:
# 解析数据资产路径,提取数据存储名称 datastore_name = data_asset.path.split("/")[2] datastore = ml_client.datastores.get(datastore_name) # 构建存储账户连接字符串 connection_string = ( f"DefaultEndpointsProtocol=https;AccountName={datastore.account_name};" f"AccountKey={datastore.account_key};EndpointSuffix=core.windows.net" ) # 获取容器名和数据资产对应的文件前缀 container_name = datastore.container_name prefix = "/".join(data_asset.path.split("/")[4:]) if len(data_asset.path.split("/")) > 4 else ""
步骤4:遍历并下载所有jsonl文件
遍历目标路径下的所有jsonl文件,下载到本地指定目录:
# 初始化Blob客户端 blob_service_client = BlobServiceClient.from_connection_string(connection_string) container_client = blob_service_client.get_container_client(container_name) # 本地存储目录,替换为你需要的路径 local_dir = "./train_jsonl_files" os.makedirs(local_dir, exist_ok=True) # 遍历并下载jsonl文件 for blob in container_client.list_blobs(name_starts_with=prefix): if blob.name.endswith(".jsonl"): # 构建本地文件路径,保留原目录结构 local_file_path = os.path.join(local_dir, os.path.relpath(blob.name, prefix)) os.makedirs(os.path.dirname(local_file_path), exist_ok=True) # 下载文件 with open(local_file_path, "wb") as f: f.write(container_client.download_blob(blob).readall()) print(f"已下载:{blob.name} -> {local_file_path}")
注意事项
- 若数据资产路径是Blob存储的公开URL/SAS URL,可直接用该URL初始化
BlobServiceClient,无需通过数据存储获取连接信息。 - 确保所用身份凭证拥有访问Azure ML注册表和对应存储账户的权限(如Storage Blob Data Contributor角色)。
内容的提问来源于stack exchange,提问作者beepretty
相关产品推荐
相关产品推荐

