How to change owner of a file in python

Question:

I am trying to change owner of a file. I am currently logged as user1 and trying to set ownership to user2. I need to run chown as sudo(root) because the parent directory’s permissions does not allow user1 to change ownership.

When I run the following code I get an error:

>>> getpass.getuser() #current user
'user1'

>>> os.chown("/me.txt", uid, gid)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 1] Operation not permitted: '/me.txt'

where uid and gid are for user2.

Asked By: codec

||

Answers:

Use sudo if user1 has permission to run sudo chown. It may ask for a password:

import os
os.system("sudo chown user2 /me.txt")
Answered By: Yusuf N

A more pythonic way to accomplish this (i.e. not just using Python to run a shell command) would be to use os.chown(). For example, to pythonically change data.json ownership from root user to the current user running the script:

import os
from pwd import getpwnam


file = "data.json"
if path.owner() == 'root';
  user = os.getlogin()
  uid = getpwnam(user).pw_uid
  gid = getpwnam(user).pw_gid
  os.chown(path,uid,gid) # now `chown` the file to the current user
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.