Python Forum
Sorting os.dirscan() result - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sorting os.dirscan() result (/thread-28141.html)



Sorting os.dirscan() result - SamParker - Jul-07-2020

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


RE: Sorting os.dirscan() result - bowlofred - Jul-07-2020

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'>]



RE: Sorting os.dirscan() result - menator01 - Jul-07-2020

Have a look at os.walk


This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.