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)
Thanks, fixed
Thanks a lot, it’s exactly what I was looking for. Very useful.
Luca
Wow, awesome. Thanks
thx! very useful!
Very nice, also if you use numpy you can also do something like this, using array’s built in argsort method
import numpy
dirs=array(os.listdir(‘./’))
dirs=dirs[dirs.argsort()]
If you have a directory with 100,000 listings, you might want to write a more efficient code function. Here’s a whack at it.
import os
def custom_listdir(path):
"""
Returns the content of a directory by showing directories first
and then files by ordering the names alphabetically
"""
all = sorted(os.listdir(path)); dirs = []
for i in xrange(len(all)-1, -1, -1):
if os.path.isdir(path + os.path.sep + all[i]):
dirs.append(all.pop(i))
dirs.extend(all)
Ah, my indents got removed from the above comment. You can prolly figure it out. It removes directories from variable all into variable dirs. Then adds the files left in variable all to the end of variable dirs.