使用Python列出具有特定名称类型的Azure容器

时间:2019-03-27 16:55:09

标签: python azure azure-storage-blobs

我正在尝试列出一堆具有特定名称类型的azure容器-它们都被称为cycling-asset-group-x,其中x是数字或字母。自行车资产组a,自行车资产组1,自行车资产组b,自行车资产组2。

我只想打印后缀为数字的容器,即cycling-asset-group-1,cycling-asset-group-2等

我该怎么做?到目前为止,这是我要做的事情:

account_name   = 'name'
account_key    = 'key'

# connect to the storage account 
blob_service   = BaseBlobService(account_name = account_name, account_key = account_key)
prefix_input_container = 'cycling-asset-group-'

# get a list of the containers - I think it's something like this...? 
cycling_containers = blob_service.list_containers("%s%d" % (prefix_input_container,...)) 

for c in cycling_containers:
    contname = c.name
    print(contname)

1 个答案:

答案 0 :(得分:1)

只需将您的prefix_input_container值传递给prefix的方法list_containers的参数BaseBlobService,如下所示。请参阅API参考BaseBlobService.list_containers

  

list_containers(前缀=无,num_results =无,include_metadata = False,标记=无,超时=无)[源代码]

     

参数:
  前缀(str)–过滤结果以仅返回名称以指定前缀开头的容器。

prefix_input_container = 'cycling-asset-group-'

cycling_containers = blob_service.list_containers(prefix=prefix_input_container) 

# Import regex module to filter the results
import re
re_expression = r"%s\d+$" % prefix_input_container
pattern = re.compile(re_expression)

# There are two ways.
# No.1 Create a generator from the generator of cycling_containers 
filtered_cycling_container_names = (c.name for c in cycling_containers if pattern.match(c.name))
for contname in filtered_cycling_container_names:
    print(contname)

# No.2 Create a name list
contnames = [c.name for c in cycling_containers if pattern.match(c.name)]
print(contnames)