Get unix file type using Python os module

I would like to get a unix file type file given in the path (figure out if it is a regular file, named pipe, block device, ...)

I found in the docs os.stat(path).st_type

, but in Python 3.6 this seems to be broken.

Another approach is to use objects os.DirEntry

(for example os.listdir(path)

), but there are only methods is_dir()

, is_file()

and is_symlink()

.

Any ideas how to do this?

+3


source to share


2 answers


Python 3.6 has pathlib

, and its objects Path

have methods:

  • is_dir()

  • is_file()

  • is_symlink()

  • is_socket()

  • is_fifo()

  • is_block_device()

  • is_char_device()



pathlib

it takes a little getting used to (at least for me when I came to Python from C / C ++ to Unix) but it's a good library

+1


source


You are using a module stat

to interpret the result 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 generic function to return a specific 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>

      

+2


source







All Articles