Welcome to Microsoft Q&A platform and thanks for posting your question here.
To get the size of a specified container in Azure Blob Storage using the Python API, you can list all the blobs in the container and sum up their sizes. Here’s a sample code snippet which will share the output in the terminal and also creates a file in the same directory where the script is stored:
from azure.storage.blob import BlobServiceClient
# Create the BlobServiceClient that is used to call the Blob service for the storage account
conn_str = '<update the connecion string>'
blob_service_client = BlobServiceClient.from_connection_string(conn_str=conn_str)
all_containers = blob_service_client.list_containers()
for container in all_containers:
# List the blobs in the container
with open('output.txt', 'a') as file:
# Write your output
file.write("\nContainer Name : " + container['name'])
print("\nContainer Name : " + container['name'])
container_name = container['name']
container = blob_service_client.get_container_client(container=container_name)
lblobs = container.list_blobs()
# Initialize the size
total_size = 0
# Loop through each blob and add up the sizes
for blob in lblobs:
with open('output.txt', 'a') as file:
file.write(" \n\tBlob name: " + blob.name + " Blob size(bytes): "+ str(blob.size))
print("\tBlob name: " + blob.name + " Blob size(bytes): "+ str(blob.size))
total_size += blob.size
with open('output.txt', 'a') as file:
file.write("\nTotal size of the container(bytes): " + container_name +" " + str(total_size))
print("Total size of the container(bytes): " + container_name +" " + str(total_size))
Hope this helps. Thanks