Tag Archives: path

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