How to use Python Api to check the size of Blob container?

Hua, Manson (Shanghai) 20 Reputation points
2023-11-23T03:23:26.69+00:00

There are multiple containers in each blob, I want to use the Python API to see the size of the specified container, how do I do it?

Azure Blob Storage
Azure Blob Storage
An Azure service that stores unstructured data in the cloud as blobs.
2,598 questions
{count} votes

1 answer

Sort by: Most helpful
  1. SAMIT SARKAR 791 Reputation points Microsoft Employee
    2023-11-23T15:39:15.6333333+00:00

    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