Python 3.3+Linux · macOSshutilfunction
shutil.chown()
system and environment
Changes a file's owner and/or group; accepts user and group names, not only numeric ids. Unix only (Linux, macOS).
Syntax
shutil.chown(path, user=None, group=None, *, dir_fd=None, follow_symlinks=True)
Unlike os.chown, which needs both numbers (uid and gid, -1 meaning 'keep'), here you can give just one, by name: chown(p, group='www-data'). Neither user nor group raises ValueError, an unknown name raises LookupError. Only root can give a file to another user: an ordinary user gets PermissionError. The function does not exist on Windows.
Examples
import os, shutil
open('a.txt', 'w').close()
shutil.chown('a.txt', group=os.getgid()) # своя группа — разрешено всем
try:
shutil.chown('a.txt')
except ValueError as e:
print(e) # → user and/or group must be set
try:
shutil.chown('a.txt', user='no_such_user_xyz')
except LookupError as e:
print(e) # → no such user: 'no_such_user_xyz'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy