How to Delete Blob in Azure Storage: Simple Guide
To delete a blob in Azure, use the
delete_blob() method from the Azure Blob Storage client. You first create a BlobClient for the target blob, then call delete_blob() to remove it from the container.Syntax
The basic syntax to delete a blob in Azure Storage using Python SDK is:
BlobClient: Represents the blob to delete.delete_blob(): Method that deletes the blob.
python
from azure.storage.blob import BlobClient blob_client = BlobClient.from_connection_string(conn_str="<your_connection_string>", container_name="<container>", blob_name="<blob_name>") blob_client.delete_blob()
Example
This example shows how to delete a blob named sample.txt from a container called mycontainer. It connects to Azure Storage using a connection string and deletes the blob.
python
from azure.storage.blob import BlobClient # Replace with your Azure Storage connection string connection_string = "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net" container_name = "mycontainer" blob_name = "sample.txt" blob_client = BlobClient.from_connection_string(conn_str=connection_string, container_name=container_name, blob_name=blob_name) blob_client.delete_blob() print(f"Blob '{blob_name}' deleted successfully from container '{container_name}'.")
Output
Blob 'sample.txt' deleted successfully from container 'mycontainer'.
Common Pitfalls
Common mistakes when deleting blobs include:
- Using incorrect container or blob names causes
ResourceNotFoundError. - Not having proper permissions leads to
ClientAuthenticationError. - Trying to delete a blob that is already deleted or does not exist.
Always verify your connection string and names before calling delete_blob().
python
from azure.storage.blob import BlobClient from azure.core.exceptions import ResourceNotFoundError blob_client = BlobClient.from_connection_string(conn_str="<conn_str>", container_name="wrongcontainer", blob_name="missingblob.txt") try: blob_client.delete_blob() except ResourceNotFoundError: print("Blob or container not found. Check names and try again.")
Output
Blob or container not found. Check names and try again.
Quick Reference
Tips for deleting blobs in Azure:
- Use
BlobClientto target the specific blob. - Call
delete_blob()to remove it. - Handle exceptions for missing blobs or permission issues.
- Ensure your connection string is correct and has delete permissions.
Key Takeaways
Use BlobClient and its delete_blob() method to delete blobs in Azure Storage.
Always verify container and blob names to avoid errors.
Ensure your Azure credentials have permission to delete blobs.
Handle exceptions to manage missing blobs or authentication issues gracefully.