如何以天蓝色提取容器中所有文件的完整路径

问题描述 投票:0回答:1

如何使用python获取azure容器下每个目录的列表?我似乎找不到有关如何执行此操作的文档,但与此同时,我还是azure及其术语的新手,因此可能也无济于事。

例如,我可能有一个名为* sales_data的容器,在它下面可能有:

  • 产品1 /美国
  • 产品1 /国际— sales_reps / data
  • stores / 50_different_subfolders_here
  • new_folders_created_all_the_time_here / new_sub_folders_here

我想要一个列出每个目录的完整路径的列表。我从这里去哪里?

blobService = BlockBlobService(account_name = my_account_name, token_credential=my_azure_creds)

我已经弄清楚了如何获得终端目录中所有文件的清单,如下所示,但是再次找不到路径说明...

prefix_objects = blobService.list_blobs('sales_data', prefix='/product1/usa/')
for each_file in prefix_objects:
     print(each_file.name)
python azure azure-storage-blobs azure-sdk
1个回答
0
投票

这是一个完整的示例(对于SDK 12.0.0版本,它将在特定容器下找到所有文件的完整路径。

要运行以下代码,您将需要检索您感兴趣的存储帐户的连接字符串。


import os
from azure.storage.blob import BlobServiceClient

def ls_files(client, path, recursive=False):
    '''
    List files under a path, optionally recursively
    '''
    if not path == '' and not path.endswith('/'):
      path += '/'

    blob_iter = client.list_blobs(name_starts_with=path)
    files = []
    for blob in blob_iter:
      relative_path = os.path.relpath(blob.name, path)
      if recursive or not '/' in relative_path:
        files.append(relative_path)
    return files

# Connection string for the storage account.
connection_string = ''

# Name of the container you are interested in.
container_name = 'sales_data'

blob_service_client = BlobServiceClient.from_connection_string(connection_string)
client = blob_service_client.get_container_client(container_name)

files = ls_files(client, '', recursive=True)

Note:函数ls_files来自this repo

该源代码的所有功劳归作者rakshith91。

© www.soinside.com 2019 - 2024. All rights reserved.