R overflow
R overflow

Reputation: 1352

Is it possible to read in all the files from an Azure Blob Storage container, and deleting the files after reading with Python?

I would like to read all files from an Azure Blob storage container, and save them on my local computer. After saving them on my local computer, I would like to delete the ones from Blob storage.

I found this solution on stack. However, that was just for reading one single blob file (where you need to specify the name of the file).

# The example from stack, to read in 1 file. 
from azure.storage.blob import BlockBlobService

block_blob_service = BlockBlobService(account_name='myaccount', account_key='mykey')
block_blob_service.get_blob_to_path('mycontainer', 'myblockblob', 'out-sunset.png')

Upvotes: 0

Views: 1083

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136196

It's actually pretty straightforward. You just need to list blobs and then download each blob individually.

Something like:

from azure.storage.blob import BlockBlobService

block_blob_service = BlockBlobService(account_name='myaccount', account_key='mykey')

#list blobs in container
blobs = block_blob_service.list_blobs(container_name='mycontainer')

for blob in blobs:
    #download each blob
    block_blob_service.get_blob_to_path(container_name='mycontainer', blob_name=blob.name, file_path=blob.name)
    #delete blob
    #block_blob_service.delete_blob(container_name='mycontainer', blob_name=blob.name)

Please note that above code assumes that you don't have blobs inside virtual folders inside your blob container and will fail if you have blobs inside virtual folders in a blob container. You will need to create a directory on the local file system first.

Upvotes: 2

Related Questions