When I run os.walk(), I get my results in alphanumeric order; starting from 0, ending at z. Is it possible to reverse this?
So if I have 3 directories; apple/, bananas/, pears/, I would want pears/, bananas/ and apples/ returned.
Obviously I could store all the dirs as a list and then .reverse() but that’s going to take a long time.
First of all,
os.walk()does not specify the order in which the directories are returned, so if I were you I wouldn’t rely on the alphabetic order.Having said that, you can choose the order in which the subdirectories are traversed by leaving
topdownset to its default value (True), and then sortingdirsin-place:That’ll make
os.walk()traverse the subdirectories in reverse lexicographic order of their names.The documentation explains how this works: