How to set a files owner in python?

Question:

Firstly is it possible to set a file’s owner with python?
And if so how do you set a file’s owner with python?

Asked By: Jay

||

Answers:

os.chown(path, uid, gid)

http://docs.python.org/library/os.html

The uid and gid can be retrieved from a string by

import pwd
import grp
import os

uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid

Reference: How to change the user and group permissions for a directory, by name?

Answered By: Maria Zverina

Old, but might help in the future for those who wish to set files owner in windows.

*I have yet to find a pure ‘pythonic’ method, this is the alternative:

Windows provides the following takeown.exe utility which we will take advantage of:

takeown /f folder_path /r /d Y (‘r’ for recursively take ownership on all files and folders in the tree and ‘d’ for default input parameter that will allow to take ownership on all filesfolders).
further documentation : msdn docs

Code sample:

from subprocess import STDOUT, check_output
check_output(["takeown", "/f", path_, "/r", "/d", "Y"], stderr=STDOUT)
Answered By: Guy Tabak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.