Python listdir order

Just a quick tip. If you’re using the python’s os.listdir() func­tion you may be not happy at all with the way it orders results. The fol­low­ing code snip­pet orders the result of the list­dir so it shows direc­to­ries 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
  1. Cool!

    But to use you have to add an s in the return state­ment… (return dirs)

  2. Thanks a lot, it’s exactly what I was look­ing for. Very useful.

    Luca

  3. Wow, awe­some. Thanks

  4. thx! very useful!

  5. Very nice, also if you use numpy you can also do some­thing like this, using array’s built in argsort method

    import numpy

    dirs=array(os.listdir(‘./’))
     dirs=dirs[dirs.argsort()]

  6. If you have a direc­tory with 100,000 list­ings, you might want to write a more effi­cient code func­tion. 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)

  7. Ah, my indents got removed from the above com­ment. You can prolly figure it out. It removes direc­to­ries from vari­able all into vari­able dirs. Then adds the files left in vari­able all to the end of vari­able dirs.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">