Python listdir order
February 15th, 2008
Just a quick tip. If you’re using the python’s os.listdir() function you may be not happy at all with the way it orders results. The following code snippet orders the result of the listdir so it shows directories first and then files, and sorts these two groups alphabetically:
import os
def custom_listdir(path):
"""
Returns the content of a directory by showing directories first
and then files by ordering the names alphabetically
"""
dirs = sorted([d for d in os.listdir(path) if os.path.isdir(path + os.path.sep + d)])
dirs.extend(sorted([f for f in os.listdir(path) if os.path.isfile(path + os.path.sep + f)]))
return dirs
Cool!
But to use you have to add an s in the return statement… (return dirs)
Comment by falstaff — June 23rd, 2008 at 21:49
Thanks, fixed
Comment by Giuliani Vito, Ivan — June 25th, 2008 at 23:01
Thanks a lot, it’s exactly what I was looking for. Very useful.
Luca
Comment by Clem — January 12th, 2010 at 11:24
Wow, awesome. Thanks
Comment by cnewman — July 13th, 2010 at 18:29
thx! very useful!
Comment by nicolo — July 29th, 2010 at 11:55