Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting os.dirscan() result
#1
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
Reply
#2
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'>]
Reply
#3
Have a look at os.walk
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 3,047 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020