Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save brijrajsingh/35cd591c2ca90916b27742d52a3cf6ba to your computer and use it in GitHub Desktop.
Save brijrajsingh/35cd591c2ca90916b27742d52a3cf6ba to your computer and use it in GitHub Desktop.
Downloadin an Azure Storage Blob Container with complex path of folders and sub folders
from azure.storage.blob import BlockBlobService
from azure.storage.blob import PublicAccess
import os
#name of your storage account and the access key from Settings->AccessKeys->key1
block_blob_service = BlockBlobService(account_name='storageaccountname', account_key='AccountKey')
#name of the container
generator = block_blob_service.list_blobs('testcontainer')
#code below lists all the blobs in the container and downloads them one after another
for blob in generator:
print(blob.name)
print("{}".format(blob.name))
#check if the path contains a folder structure, create the folder structure
if "/" in "{}".format(blob.name):
print("there is a path in this")
#extract the folder path and check if that folder exists locally, and if not create it
head, tail = os.path.split("{}".format(blob.name))
print(head)
print(tail)
if (os.path.isdir(os.getcwd()+ "/" + head)):
#download the files to this directory
print("directory and sub directories exist")
block_blob_service.get_blob_to_path('testcontainer',blob.name,os.getcwd()+ "/" + head + "/" + tail)
else:
#create the diretcory and download the file to it
print("directory doesn't exist, creating it now")
os.makedirs(os.getcwd()+ "/" + head, exist_ok=True)
print("directory created, download initiated")
block_blob_service.get_blob_to_path('testcontainer',blob.name,os.getcwd()+ "/" + head + "/" + tail)
else:
block_blob_service.get_blob_to_path('testcontainer',blob.name,blob.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment