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
Active
Viewed 3.0k times
32
-
Presumably this is on a UNIX (like) operating system? Also, http://whathaveyoutried.com. – Martijn Pieters May 30 '12 at 14:56
2 Answers
60
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?

Community
- 1
- 1

Maria Zverina
- 10,863
- 3
- 44
- 61
0
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 files\folders). further documentation : msdn docs
Code sample:
from subprocess import STDOUT, check_output
check_output(["takeown", "/f", path_, "/r", "/d", "Y"], stderr=STDOUT)

Guy Tabak
- 128
- 7
-
2takeown /d /y only works for English. If you're running German, etc, the 'Y' option isn't correct (J in German, etc). Not a super reliable way to do this. – Jason Floyd Jul 30 '19 at 21:51
-
2@JasonFloyd Oh jeez. I can't tell which is the worse decision: Making program options locale-dependent, or using Windows for serious development. – xjcl Dec 21 '20 at 09:13