Azure Blob Storage Using Python
2 min readFeb 8, 2022
What is Blob:-
- Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. You’ll upload, download, and list blobs, and you’ll create and delete containers.
You have to install the Azure Blob Storage client library for Python
pip install azure-storage-blob
How to Get the connection string:-
- Inside Security +Networking
- Click on Access Key
- In that You Will Get Connection String.
How Configure your storage connection string:-
Configuration process is Operating System Dependent:-
Windows:-
setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"
Linux/Mac:-
export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"
How to Connect to Account:-
# Create the BlobServiceClient object which will be used to create a container clientblob_service_client=BlobServiceClient.from_connection_string(connect_str)
How to Create a container:-
# Create a unique name for the container container_name = str(uuid.uuid4())
# Create the container
container_client=blob_service_client.create_container(container_name)
How to Upload blobs to a container:-
# Create a local directory to hold blob data
local_path = “./data”
os.mkdir(local_path)# Create a file in the local data directory to upload and download
local_file_name = str(uuid.uuid4()) + “.txt”upload_file_path = os.path.join(local_path, local_file_name)# Write text to the file
file = open(upload_file_path, ‘w’)
file.write(“Hello, World!”)
file.close()# Create a blob client using the local file name as the name for the blob
blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)
print(“\nUploading to Azure Storage as blob:\n\t” + local_file_name)
# Upload the created file
with open(upload_file_path, “rb”) as data:
blob_client.upload_blob(data)
How to List the blobs in a container:-
blob_list = container_client.list_blobs()
for blob in blob_list:
print("\t" + blob.name)
How to Download Blobs:-
download_file_path = os.path.join(local_path, str.replace(local_file_name ,'.txt', 'DOWNLOAD.txt'))print("\nDownloading blob to \n\t" + download_file_path)
with open(download_file_path, "wb") as download_file: download_file.write(blob_client.download_blob().readall())