Home > Mobile >  To get only list of subfolder names in Directory in Azure Data Lake using Python
To get only list of subfolder names in Directory in Azure Data Lake using Python

Time:10-27

I have data in Azure data lake container named infaqa and directories in infaqa as below path: `infqa/EIM//Sales/Raw/APXTConga4__Composer_Setting__mdt, infqa/EIM//Sales/Raw/Account etc.

I am using Azure notebooks and libraries like blobserviceclient to list blobs, but I see all list of sub folders and sub sub folders keep listing. Where as I am looking for only subfolder names in a list like ['APXTConga4__Composer_Setting__mdt','Account'...] from the output which is showcased below

    Input:
        blobPrefix = "/EIM/Sales/Raw/"     
        mylist=[]
        objects=[]
        blob_list = container_client.list_blobs(blobPrefix)
        for blob in blob_list:
            mylist.append(blob.name)
            print(blob.name)
    
    Ouptut:
    EIM/Sales/Raw/APXTConga4__Composer_Setting__mdt
    EIM/Sales/Raw/APXTConga4__Composer_Setting__mdt/2020
    EIM/Sales/Raw/APXTConga4__Composer_Setting__mdt/2020/12
    EIM/Sales/Raw/APXTConga4__Composer_Setting__mdt/2020/12/02
    EIM/Sales/Raw/Account
    EIM/Sales/Raw/Account/2020
    EIM/Sales/Raw/Account/2020/12
    EIM/Sales/Raw/Account/2020/12/02

CodePudding user response:

Try with this solution ,I tried in my system

I have folder structure like where test container and account is folder

1)test/account/main/sub1/
2)test/account/test1/sub2
3)test/account/test2/sub3


from azure.storage.blob import BlobServiceClient
import os

source_key = 'Key'
source_account_name = 'Account Name'
block_blob_service = BlobServiceClient(
    account_url=f'https://{source_account_name}.blob.core.windows.net/', credential=source_key)
source_container_client = block_blob_service.get_container_client(
    'Container name')
result=[]
allfolders=[]
generator =source_container_client.list_blobs("account")

for file in source_container_client.walk_blobs('account/', delimiter='/'):
    print(file.name)
    text=file.name
    result.append(text)
for data in result:
    
    allfolders.append(data.replace("account/",""))
print(allfolders)
for res in allfolders:
    print(res)

OUTPUT

Folder structure in storage account

enter image description here

enter image description here

Able to get all subfolder names

enter image description here

  • Related