Azure Blob Storage Python SDK: Upload & Download Samples

This page provides practical Python code examples demonstrating how to upload and download files to and from Azure Blob Storage using the official Azure SDK for Python.

Prerequisites

Before running these examples, ensure you have:

Security Best Practice: Never hardcode your connection string or account key directly in your code. Use environment variables or Azure Key Vault for secure credential management.

1. Uploading a File to Blob Storage

This example shows how to upload a local file to a specified blob container.


from azure.storage.blob import BlobServiceClient, ContentSettings

def upload_blob(connection_string, container_name, local_file_path, blob_name):
    """
    Uploads a local file to an Azure Blob Storage container.

    Args:
        connection_string (str): The connection string for your Azure Storage account.
        container_name (str): The name of the blob container.
        local_file_path (str): The path to the local file to upload.
        blob_name (str): The name to give the blob in the container.
    """
    try:
        # Create the BlobServiceClient object
        blob_service_client = BlobServiceClient.from_connection_string(connection_string)

        # Get a client to interact with the specific blob
        blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)

        print(f"Uploading {local_file_path} to {blob_name}...")

        with open(local_file_path, "rb") as data:
            # Upload the file
            blob_client.upload_blob(data, overwrite=True) # overwrite=True will replace if blob already exists

        print("Upload complete.")

    except Exception as ex:
        print(f"Error uploading blob: {ex}")

if __name__ == "__main__":
    # Replace with your actual values
    # It's highly recommended to load these from environment variables or a secure configuration
    storage_connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
    my_container_name = "your-container-name"
    my_local_file_path = "path/to/your/local/file.txt" # e.g., "my_document.pdf"
    my_blob_name = "uploaded-file.txt" # The name it will have in blob storage

    if storage_connection_string == "YOUR_AZURE_STORAGE_CONNECTION_STRING":
        print("Please replace 'YOUR_AZURE_STORAGE_CONNECTION_STRING' with your actual connection string.")
    else:
        # Create a dummy file for demonstration if it doesn't exist
        try:
            with open(my_local_file_path, "x") as f:
                f.write("This is a sample file for uploading to Azure Blob Storage.\n")
            print(f"Created dummy file: {my_local_file_path}")
        except FileExistsError:
            pass # File already exists, no need to create

        upload_blob(storage_connection_string, my_container_name, my_local_file_path, my_blob_name)
                

Explanation:

2. Downloading a File from Blob Storage

This example demonstrates how to download a blob from a container to your local file system.


from azure.storage.blob import BlobServiceClient

def download_blob(connection_string, container_name, blob_name, local_download_path):
    """
    Downloads a blob from an Azure Blob Storage container to a local file.

    Args:
        connection_string (str): The connection string for your Azure Storage account.
        container_name (str): The name of the blob container.
        blob_name (str): The name of the blob to download.
        local_download_path (str): The path where the downloaded file will be saved.
    """
    try:
        # Create the BlobServiceClient object
        blob_service_client = BlobServiceClient.from_connection_string(connection_string)

        # Get a client to interact with the specific blob
        blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)

        print(f"Downloading {blob_name} to {local_download_path}...")

        with open(local_download_path, "wb") as download_file:
            download_file.write(blob_client.download_blob().readall())

        print("Download complete.")

    except Exception as ex:
        print(f"Error downloading blob: {ex}")

if __name__ == "__main__":
    # Replace with your actual values
    storage_connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
    my_container_name = "your-container-name"
    my_blob_name_to_download = "uploaded-file.txt" # The name of the blob in storage
    my_local_download_path = "downloaded_file.txt" # The name of the file locally

    if storage_connection_string == "YOUR_AZURE_STORAGE_CONNECTION_STRING":
        print("Please replace 'YOUR_AZURE_STORAGE_CONNECTION_STRING' with your actual connection string.")
    else:
        download_blob(storage_connection_string, my_container_name, my_blob_name_to_download, my_local_download_path)
                

Explanation:

3. Listing Blobs in a Container

It's often useful to see what's already in your container.


from azure.storage.blob import BlobServiceClient

def list_blobs(connection_string, container_name):
    """
    Lists all blobs in a specified Azure Blob Storage container.

    Args:
        connection_string (str): The connection string for your Azure Storage account.
        container_name (str): The name of the blob container.
    """
    try:
        blob_service_client = BlobServiceClient.from_connection_string(connection_string)
        container_client = blob_service_client.get_container_client(container_name)

        print(f"Blobs in container '{container_name}':")
        blob_list = container_client.list_blobs()

        for blob in blob_list:
            print(f"- {blob.name} (Size: {blob.size} bytes)")

    except Exception as ex:
        print(f"Error listing blobs: {ex}")

if __name__ == "__main__":
    # Replace with your actual values
    storage_connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
    my_container_name = "your-container-name"

    if storage_connection_string == "YOUR_AZURE_STORAGE_CONNECTION_STRING":
        print("Please replace 'YOUR_AZURE_STORAGE_CONNECTION_STRING' with your actual connection string.")
    else:
        list_blobs(storage_connection_string, my_container_name)
                

Further Resources

For more advanced scenarios, error handling, or other Azure Blob Storage operations, please refer to the official documentation:

You can also find the complete source code for these examples and more on our GitHub repository:

View on GitHub