在Python Azure中检查blob是否存在

7
3个回答

14

2020年9月10日发布的版本12.5.0现在在新的SDK中具有exists方法。

例如:

同步:

from azure.storage.blob import BlobClient

blob = BlobClient.from_connection_string(conn_str="my_connection_string", container_name="mycontainer", blob_name="myblob")
exists = blob.exists()
print(exists)

异步:

import asyncio

async def check():
    from azure.storage.blob.aio import BlobClient
    blob = BlobClient.from_connection_string(conn_str="my_connection_string", container_name="mycontainer", blob_name="myblob")
    async with blob:
        exists = await blob.exists()
        print(exists)

这个方法需要近一秒钟的时间来检查 blob 是否存在,有没有更快的方法可以实现? - RaphWork
1
你能试一下异步IO的变体吗?更新的答案包括异步代码片段。 - krishg
文档中缺少exists方法:https://learn.microsoft.com/en-us/azure/developer/python/sdk/storage/azure-storage-blob/azure.storage.blob.blobclient?view=storage-py-v12#methods - dparkar
1
exists()方法返回true,即使blob不存在,这会导致blob.delete_blob()出错。 - Brady

0

正如 @krshg 建议的那样,检查 blob 文件是否存在的最简单方法是

from azure.storage.blob import BlobClient
conn_str = "my_connection_string"
my_blob_name = "my_dir/my_blob"


blob = BlobClient.from_connection_string(conn_str=conn_str, container_name="mycontainer", blob_name=my_blob_name )
exists = blob.exists()
print(exists)

然而,我有一个小问题需要获取连接字符串。我正在使用 Azure 存储资源管理器。如果您也是这样做的话,您可以通过单击存储资源并在左下角面板上获取连接字符串: enter image description here 另一件事是,如果容器中有包含您 Blob 文件的目录,您可以轻松地将路径格式用于您的文件。


-1
from azure.storage.blob import BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
all_containers = blob_service_client.list_containers()
print([container['name'] for container in all_containers])

上面的代码片段将列出所有容器,我们可以从中检查容器是否存在。但请注意,输出是分页的,因此如果您有大量的容器,则需要使用续订令牌迭代输出。请参阅更多信息:https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L573


6
不建议只提供代码式回答。请提供您的回答如何解决问题以及为什么可能比其他提供的答案更可取的总结说明。 "Code only answers are discouraged. Please provide a summary of how your answer solves the problem and why it may be preferable to the other answers provided." (不建议仅提供代码答案。请提供如何解决问题的概要以及为什么这可能比提供的其他答案更可取的原因。) - DaveL17

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接