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

在VS Code中通过Python连接Azure Storage Blob存储遇阻,求示例代码

Python连接Azure Blob存储示例代码

前置准备

  • 安装Azure Blob存储Python SDK:pip install azure-storage-blob
  • 获取Azure存储账户的连接字符串或账户名称+账户密钥(可在Azure门户的存储账户「访问密钥」页面获取)

方式一:使用连接字符串连接

from azure.storage.blob import BlobServiceClient

# 替换为你的存储账户连接字符串
connect_str = "你的存储账户连接字符串"

try:
    # 初始化Blob服务客户端
    blob_service_client = BlobServiceClient.from_connection_string(connect_str)
    
    # 列出存储账户下所有容器
    print("存储账户中的容器:")
    for container in blob_service_client.list_containers():
        print(f"- {container.name}")
        
except Exception as ex:
    print(f"操作出错: {ex}")

方式二:使用账户名称和密钥连接

from azure.storage.blob import BlobServiceClient

# 替换为你的存储账户名称和密钥
account_name = "你的存储账户名称"
account_key = "你的存储账户密钥"
endpoint = f"https://{account_name}.blob.core.windows.net"

try:
    # 初始化Blob服务客户端
    blob_service_client = BlobServiceClient(account_url=endpoint, credential=account_key)
    
    # 上传本地文件到指定容器
    container_name = "test-container"  # 替换为你的目标容器名称
    blob_name = "demo.txt"  # 上传后Blob的名称
    local_file_path = "./local_demo.txt"  # 本地文件路径
    
    # 获取容器客户端
    container_client = blob_service_client.get_container_client(container_name)
    # 执行上传(overwrite=True表示覆盖同名Blob)
    with open(local_file_path, "rb") as data:
        container_client.upload_blob(name=blob_name, data=data, overwrite=True)
    print(f"文件 {local_file_path} 已上传至容器 {container_name},Blob名称:{blob_name}")
    
except Exception as ex:
    print(f"操作出错: {ex}")

常用Blob操作示例

  • 下载Blob到本地:
# 获取Blob客户端
blob_client = container_client.get_blob_client(blob_name)
# 下载文件到本地
with open("./downloaded_demo.txt", "wb") as download_file:
    download_file.write(blob_client.download_blob().readall())
print(f"Blob {blob_name} 已下载到本地")
  • 删除指定Blob:
blob_client.delete_blob()
print(f"Blob {blob_name} 已删除")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:30:59