如何获取容器中所有级别的所有 blob?

How do I get all blobs at all levels in a container?

我找到了 this 个关于在容器中列出 blob 的帖子。

from azure import *
from azure.storage import *

blob_service = BlobService(account_name='<accountname>', account_key='<accountkey>')
next_marker = None
while True:
    blobs = blob_service.list_blobs('<containername>', maxresults=100, marker=next_marker)
    next_marker = blobs.next_marker
    print(next_marker)
    print(len(blobs))
    if next_marker is None:
        break
print "done"

但是,这只会列出特定容器中的 blob。我将如何获取子文件夹中的所有 blob?我有几个级别的子文件夹,我想从父容器中获取所有数据文件的名称。

您发布的代码无效...

下面是使用 Microsoft Azure SDK for Python 3.4 的 Python 代码,它将列出所有 blob 名称(带有完整的 "subfolder" 路径,例如 project1/images/image1.png) 在特定容器中。

如果您希望获取存储帐户中所有容器中的所有 blob 名称,只需执行 blob_service.list_containers 遍历每个容器并列出每次迭代下的所有 blob。

这也是一篇关于如何使用来自 Python 的 Azure Blob 存储的有用文章。

How to use Azure Blob storage from Python

希望对您有所帮助!

from azure.storage.blob import BlobService

blob_service = BlobService(account_name='<storage account name>', account_key='<storage account key>')

blobs = []
marker = None
while True:
    batch = blob_service.list_blobs('<blob container name>', marker=marker)
    blobs.extend(batch)
    if not batch.next_marker:
        break
    marker = batch.next_marker
for blob in blobs:
    print(blob.name)

有一个函数 list_containers() 我们可以在 https://github.com/Azure/azure-storage-python/blob/master/azure/storage/blob/baseblobservice.py#L470 看到它的目的是获取存储中的所有容器

import azure
from azure.storage.blob import BlobService

blob_service = BlobService(account_name='<account_name>', account_key='<account_key>')
containers = blob_service.list_containers()

for c in containers:
    print(c.name)

然后你可以在循环中使用容器名称调用list_blob方法。

此外,如果您在 blob 名称中定义了多个子文件夹,SO 上有一个线程 list virtual folders in azure blob storage via python API 您可以参考。

在上面认可的解决方案中稍微修改一下。 BlobService 在新版本中已被弃用,使用 BlockBlobService 代替。

import azure
from azure.storage.blob import BlockBlobService

blob_service = BlockBlobService(account_name='<account_name>', account_key='<account_key>')
containers = blob_service.list_containers()

for c in containers:
    print(c.name)

这很接近,但我不确定如何从结果中排除文件夹名称。另外,我相当确定这对存储帐户的影响非常

可能要小心了!

(假设您已将连接字符串保存为环境变量 conn_str

import os
from azure.storage.blob import BlobServiceClient


blob_svc = BlobServiceClient.from_connection_string(os.environ['conn_str'])

containers = blob_svc.list_containers()

list_of_blobs = []

for c in containers:
    container_client = blob_svc.get_container_client(c)
    blob_list = container_client.list_blobs()
    for blob in blob_list:
        list_of_blobs.append(os.path.basename(blob.name))

print(len(list_of_blobs))

我能够在 ~65 秒内 return 22k+ blob(和文件夹)名称。