all Python 3osfunction
os.fchmod
os — permissions and ownership
Like chmod, but on an open file descriptor. On Windows since Python 3.13, and only the read-only flag.
Syntax
os.fchmod(...)
It changes permissions on an already open file rather than a path, so it is immune to the race where the file is swapped between check and change. A common pattern is to create the file with restricted permissions from the start via os.open with mode, rather than open it and narrow permissions afterwards. On Windows it exists since 3.13 and changes only the read-only flag.
Examples
import os
f = open('demo_fd.txt', 'w') # → ? открываем файл и дальше работаем через его дескриптор
fd = f.fileno() # → ? номер дескриптора, например 3
os.fchmod(fd, 0o600) # → ? только Unix: то же, что os.chmod(path, 0o600), но привязано к дескриптору, а не к имени файла
print(oct(os.fstat(fd).st_mode & 0o777)) # → 0o600
os.fchmod(fd, 0o644) # → ? только Unix: открываем чтение остальным; файл могли переименовать — дескриптор всё равно указывает на него
f.close() # → ? закрываем файл, дескриптор становится недействительным
os.fchmod(fd, 0o600) # → OSError: Bad file descriptor — по закрытому дескриптору права менять нельзя
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy