all Python 3statfunction
stat.S_IFMT()
mode bits
Extracts the file-type bits from st_mode; the result is compared with constants such as S_IFREG and S_IFDIR.
Syntax
stat.S_IFMT(mode) == stat.S_IFREG
Use it when the type is looked up in a dict or a match: `kinds[stat.S_IFMT(mode)]`. Testing `mode & stat.S_IFDIR` is wrong: type codes are not separate flags, S_IFSOCK = 0o140000 and S_IFBLK = 0o060000 contain the directory bit, so a socket "turns out" to be a directory. Compare S_IFMT(mode) == constant or use S_IS*.
Examples
import os, stat
os.mkdir('d')
open('f', 'w').close()
kinds = {stat.S_IFDIR: 'каталог', stat.S_IFREG: 'файл'}
for name in ('d', 'f'):
print(name, kinds[stat.S_IFMT(os.stat(name).st_mode)]) # → d каталог / f файл
import stat
sock = stat.S_IFSOCK | 0o755
print(bool(sock & stat.S_IFDIR), stat.S_ISDIR(sock)) # → True False — маска врёт, функция нет
See also
Open in the full glossarydocs.python.orgReport an inaccuracy