Python Glossary Русский

all Python 3Linux · macOSosfunction

os.chown

os — permissions and ownership

Change a file's owner (uid) and group (gid). Availability: Unix.

Syntax

os.chown(...)

You cannot pass owner names — numeric uid and gid are required; translate names with pwd.getpwnam and grp.getgrnam, or let shutil.chown do it. A value of -1 leaves that field unchanged. Usually only root may change ownership.

Examples

import os
path = 'demo_owner.txt'
open(path, 'w').close()  # → ? создаём временный файл для опытов
os.chown(path, os.getuid(), os.getgid())  # → ? только Unix: владельцем становится текущий пользователь и его основная группа
os.chown(path, -1, os.getgid())  # → ? только Unix: -1 означает «не менять», поэтому правится лишь группа
print(os.stat(path).st_uid == os.getuid())  # → ? True: st_uid показывает владельца, установленного выше (на Unix)
os.chown(path, 0, 0)  # → ? только Unix: отдать файл root удастся лишь из-под суперпользователя, иначе PermissionError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy