Get unix file type with Python os module

You use the stat module to interpret the result of os.stat(path).st_mode.

>>> import os
>>> import stat
>>> stat.S_ISDIR(os.stat('/dev/null').st_mode)
False
>>> stat.S_ISCHR(os.stat('/dev/null').st_mode)
True

You can make a general function to return the determined type. This works for both Python 2 and 3.

import enum
import os
import stat

class PathType(enum.Enum):
    dir = 0  # directory
    chr = 1  # character special device file
    blk = 2  # block special device file
    reg = 3  # regular file
    fifo = 4  # FIFO (named pipe)
    lnk = 5  # symbolic link
    sock = 6  # socket
    door = 7  # door  (Py 3.4+)
    port = 8  # event port  (Py 3.4+)
    wht = 9  # whiteout (Py 3.4+)

    unknown = 10

    @classmethod
    def get(cls, path):
        if not isinstance(path, int):
            path = os.stat(path).st_mode
        for path_type in cls:
            method = getattr(stat, 'S_IS' + path_type.name.upper())
            if method and method(path):
                return path_type
        return cls.unknown

PathType.__new__ = (lambda cls, path: cls.get(path))
>>> PathType('/dev/null')
<PathType.chr: 1>
>>> PathType('/home')
<PathType.dir: 0>