How to change the owner of a file using Python?


You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner:

Example

import pwd
import grp
import os
uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = 'my_folder'
os.chown(path, uid, gid)

Updated on: 13-Dec-2019

944 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements