如何使用 Python 的 Azure 存储 SDK 读取 Blob 的内容?

How to read the contents of Blobs using Azure Storage SDK for Python?

我已将 Azure 包添加到我的 Anaconda 发行版中,还为 Python 安装了 Azure 存储 SDK。我正在尝试使用以下方法读取已上传到特定 blob 容器的文件:

from azure.storage import BlobService
blob_service = BlobService(account_name='azure subscription name',   
account_key='azure subscription key')

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

当我运行这个脚本时,我收到以下错误:

ImportError: No module named 'azure.storage'

如何解决此问题以便我可以读取 blob 容器中的文本文件和 PDF?

不太确定您是如何安装存储 sdk 的,或者您使用的是什么版本,但您应该只需要执行以下操作:

安装:

pip install azure-storage

导入并实例化 blob 服务:

from azure.storage.blob import BlockBlobService
blob_service = BlockBlobService(account_name="<storagename>",account_key="<storagekey>")

到那时,您应该能够列出 blob(或下载 blob,或您需要执行的任何其他操作)。

这是一个老问题,但由于最近弃用了 SDK 中的某些代码块而变得相关。

请按照以下步骤获取给定容器中的 blob 文件列表以及修改日期。

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
storageconnectionstring='yourstorageconnectionstring'
blobclient=BlobServiceClient.from_connection_string(storageconnectionstring)
containerclient=blobclient.get_container_client('yourblobcontainername')
for blobs in containerclient.list_blobs():
    print (blobs['name'],": Modified: ",blobs['last_modified'])