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:


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)