Cathy
Cathy

Reputation: 377

Accessing data of a file from Azure blob storage to a variable

I want to access data of a file from Azure blob storage to a variable.

The below code which I am using reads data of a file from Azure blob storage to a local file. I want to read it into a variable. Is it possible to do it?

from azure.storage.blob import BlockBlobService, PublicAccess

accountName='user123'
accountKey='Pass@12345'
CONTAINER_NAME='development'
blobName='4567/dummyFile.txt'
file_path='C:\\Users\\Sam\\Desktop\\testFile.txt' # local file in which the content from blob will be written


block_blob_service = BlockBlobService(account_name=accountName, account_key=accountKey)

# to access content from azure blob storage to local file
block_blob_service.get_blob_to_path(CONTAINER_NAME,blobName,file_path)

Upvotes: 1

Views: 2485

Answers (2)

santosrodriguez
santosrodriguez

Reputation: 21

This worked for me for version 12.8.1 of the azure-storage-blob package. The BlockBlobService class doesn't appear to be supported in the newer versions.

from azure.storage.blob import BlobServiceClient    # azure-storage-blob 12.8.1

connection_string = " "
local_file_name = "example.txt"
container_name = "example_container"

blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(local_file_name)
my_blob = blob_client.download_blob().readall() # read blob content as string

print(my_blob)

Upvotes: 1

Gaurav Mantri
Gaurav Mantri

Reputation: 136306

Python SDK for Azure Storage provides 3 helper methods for that purpose:

  1. get_blob_to_stream: This method will download the blob and store the contents in a stream. Use this method if you want to use a stream type variable.
  2. get_blob_to_bytes: This method will download the blob and store the contents in a byte array. Use this method if you want to use a byte array type variable.
  3. get_blob_to_text: This method will download the blob and store the contents in a string. Use this method if you want to use a string type variable. Please use this method only if you know the blob contents are string. If the contents of a blob are binary (e.g. an image file), use other two method.

Upvotes: 3

Related Questions