Azure Storage Python

Docs: Blob Storage

Deleting Blobs with the Azure Storage Python SDK

This guide explains how to delete blobs from an Azure Blob Storage container using the Azure SDK for Python. You can delete individual blobs or all blobs within a container.

Prerequisites

Connecting to Blob Storage

First, you need to establish a connection to your blob storage. You can do this using a connection string, account key, or shared access signature (SAS).


from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

# Replace with your actual connection string
connect_str = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
container_name = "your-container-name"
blob_name = "path/to/your/blob.txt"

# Create the BlobServiceClient object
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
            

Deleting a Single Blob

To delete a single blob, you use the delete_blob() method on the ContainerClient or BlobClient. You must provide the name of the blob you wish to delete.

Using ContainerClient:


# Get a client to the container
container_client = blob_service_client.get_container_client(container_name)

try:
    container_client.delete_blob(blob_name)
    print(f"Blob '{blob_name}' deleted successfully from container '{container_name}'.")
except Exception as ex:
    print(f"Error deleting blob: {ex}")
            

Using BlobClient:


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

try:
    blob_client.delete_blob()
    print(f"Blob '{blob_name}' deleted successfully from container '{container_name}'.")
except Exception as ex:
    print(f"Error deleting blob: {ex}")
            

Deleting Blobs by Prefix

You can delete multiple blobs that match a specific prefix. This is useful for cleaning up files in a particular directory structure.


prefix_to_delete = "logs/archive/"

try:
    # List blobs with the prefix and delete them
    blob_list = container_client.list_blobs(name_starts_with=prefix_to_delete)
    for blob in blob_list:
        container_client.delete_blob(blob.name)
        print(f"Deleted blob: {blob.name}")
    print(f"All blobs with prefix '{prefix_to_delete}' deleted.")
except Exception as ex:
    print(f"Error deleting blobs by prefix: {ex}")
            

Deleting All Blobs in a Container

Caution: This action will permanently remove all blobs from the specified container. Use with extreme care.

Warning: Deleting all blobs in a container is an irreversible operation. Ensure you have backups if necessary.

try:
    blob_list = container_client.list_blobs()
    for blob in blob_list:
        container_client.delete_blob(blob.name)
        print(f"Deleted blob: {blob.name}")
    print(f"All blobs deleted from container '{container_name}'.")
except Exception as ex:
    print(f"Error deleting all blobs: {ex}")
            

Handling Deletion Errors

It's good practice to wrap your deletion operations in try...except blocks to gracefully handle potential errors, such as network issues or if the blob does not exist.

Key Methods:

  • BlobServiceClient.get_container_client(container_name): Gets a client to interact with a specific container.
  • ContainerClient.delete_blob(blob_name, delete_snapshots='include'): Deletes a blob. The delete_snapshots parameter can be used to delete snapshots along with the blob.
  • BlobClient.delete_blob(): Deletes the blob represented by the BlobClient.
  • ContainerClient.list_blobs(name_starts_with=prefix): Lists blobs, optionally filtered by a prefix.

For more advanced scenarios, such as deleting blobs with specific tags or conditional deletion, refer to the official Azure Blob Storage documentation.