'Is it possible to list files in a dir with Azure storages

I'm using Django and django-storages[azure] as backend. But i can't to find out to list dir the files instead I have to use snippets like this:

block_blob_service.list_blobs(container_name='media', prefix=folderPath)]

this is not working:

listdir(absoluteFolderPath)

In storages/backend/azure_storage.py I found this part:

def listdir(self, path=''):
        """
        Return directories and files for a given path.
        Leave the path empty to list the root.
        Order of dirs and files is undefined.
        """
        files = []
        dirs = set()
        for name in self.list_all(path):
            n = name[len(path):]
            if '/' in n:
                dirs.add(n.split('/', 1)[0])
            else:
                files.append(n)
        return list(dirs), files

But how can I use it?

regards Christopher.



Solution 1:[1]

Assuming you have set DEFAULT_FILE_STORAGE you could access it through storage

from django.core.files.storage import default_storage
dirs = default_storage.listdir(absoluteFolderPath)

Solution 2:[2]

It is working thanks, but I got a list:

[[], ['ANG_65096745.pdf', 'airpods-gave.png', 'miniDP_HDMI.png', 'surface-book-2-13-in-laptop-mode-device-render.jpg', 'surface_4_color.png']]

how can I use it in a for loop? I made this:

files = default_storage.listdir(path=folderPath)
   for file in files:
   print(file)

but it will not print row for row just the output I wrote

Solution 3:[3]

The API for listdir returns a tuple of two lists, the first being the directories (folders) in the given path, the second being the files.

The correct way to unpack this would be to assign two variables during the call.

Examples:

from django.core.files.storage import default_storage

# list the contents of the root directory of the storage
directories, files = default_storage.listdir('')

# list the contents of a directory named 'images' inside 'media'
directories, files = default_storage.listdir('media/images')

# now you can iterate through just the files
for filename in files:
    print(filename)

I'm using django-storages with S3, but Azure looks to work exactly the same.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iklinac
Solution 2
Solution 3 Warwick Brown