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

如何解决Python中无法从Azure文件共享下载整个目录的问题

解决Azure文件共享目录下载问题

你当前的代码只能处理单个文件,因为get_file_client是针对单个文件的客户端,要下载整个目录,需要递归遍历目录下的所有文件和子目录,逐个下载。以下是可行的实现方案:

实现步骤

  • 使用ShareDirectoryClient获取目标目录的客户端,遍历目录内的所有条目(文件和子目录)
  • 对每个子目录,递归创建本地对应目录并继续遍历
  • 对每个文件,创建本地文件路径,下载并写入本地文件

完整代码

from azure.storage.fileshare import ShareClient, ShareDirectoryClient
import os

# 配置连接信息
connection_string = "你的Azure连接字符串"
share_name = "filshare"
remote_dir_path = "dir1/sub_idr1"
local_save_path = "./downloaded_dir"  # 本地保存目录

def download_directory(directory_client: ShareDirectoryClient, local_dir_path: str):
    # 创建本地目录(如果不存在)
    os.makedirs(local_dir_path, exist_ok=True)
    
    # 遍历目录下的所有条目
    for item in directory_client.list_directories_and_files():
        item_name = item["name"]
        remote_item_path = f"{directory_client.directory_path}/{item_name}"
        local_item_path = os.path.join(local_dir_path, item_name)
        
        if item["is_directory"]:
            # 如果是子目录,递归下载
            sub_dir_client = directory_client.get_subdirectory_client(item_name)
            download_directory(sub_dir_client, local_item_path)
        else:
            # 如果是文件,下载并保存
            file_client = directory_client.get_file_client(item_name)
            with open(local_item_path, "wb") as local_file:
                download_stream = file_client.download_file()
                local_file.write(download_stream.readall())
            print(f"已下载文件: {local_item_path}")

# 初始化ShareClient并获取目标目录客户端
share_client = ShareClient.from_connection_string(connection_string, share_name)
target_dir_client = share_client.get_directory_client(remote_dir_path)

# 开始下载
download_directory(target_dir_client, local_save_path)
print("目录下载完成")

代码说明

  1. 目录遍历:通过list_directories_and_files方法获取目录下的所有文件和子目录,区分条目类型(文件/目录)
  2. 递归处理:遇到子目录时,创建本地对应目录并递归调用下载函数
  3. 文件下载:对每个文件,打开本地文件流,读取Azure文件的下载流并写入本地

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:15:16