Hello,
I am listing objects in a directory using os.dirscan(). I need to sort the result in alphabetical order. Currently the order is random. I do not want to use os.listdir(), since I need the attributes. Please suggest Any solution
I assume you mean
os.scandir().
os.scandir() is an iterator, and for performance (especially on large directories), you'd expect to handle things in directory order. If you want alphabetical order, you have to consume all the entries and then sort it. In many cases, it might be better to get all the names with os.listdir(), and then get attributes separately.
But if you don't have huge directories and want to keep track of everything, then put all of the DirEntry objects in a list and sort them.
import os
with os.scandir("mydir") as it:
direntries = list(it) # reads all of the directory entries
print(direntries) # list in directory order
direntries.sort(key=lambda x: x.name)
print(direntries) # list in alphabetical order by name
Output:
[<DirEntry 'u'>, <DirEntry 'g'>, <DirEntry 'a'>, <DirEntry 'c'>, <DirEntry 'd'>, <DirEntry 'v'>, <DirEntry 'b'>, <DirEntry 'l'>]
[<DirEntry 'a'>, <DirEntry 'b'>, <DirEntry 'c'>, <DirEntry 'd'>, <DirEntry 'g'>, <DirEntry 'l'>, <DirEntry 'u'>, <DirEntry 'v'>]