How to use shutil.chown() Method In Python
In this example, the function change
is defined to modify both the owner and group of a specified file (path
). It first retrieves the current owner and group, then changes them to the provided uid
and gid
using shutil.chown()
.
import shutil
from pathlib import Path
def change(path, uid, gid):
try:
# Getting the owner and the group
info = Path(path)
user = info.owner()
group = info.group()
print("Present owner and group")
print("Present owner:", user)
print("Present group:", group)
# Changing the owner and the group
shutil.chown(path, uid, gid)
print("\nThe owner and the group have been changed successfully")
# Printing the owner user and group
info = Path(path)
user = info.owner()
group = info.group()
print("Present owner now:", user)
print("Present group now:", group)
except FileNotFoundError:
print("File not found:", path)
except Exception as e:
print("An error occurred:", e)
# Example usage
path = 'C:\\Users\\Lenovo\\Downloads\\Work TP\\trial.py'
uid = 10
gid = 10
change(path, uid, gid)
Output:
$ sudo python3 code2.py
[sudo] password for kislay:
Present owner and group
Present owner: kislay
Present group: kislay
The owner and the group is changed successfully
Present owner now: uucp
Present group now: uucp
How to Change the Owner of a Directory Using Python
We can change who owns a file or directory by using the pwd, grp, and os modules. The uid module is used to change the owner, get the group ID from the group name string, and get the user ID from the user name. In this article, we will see how to change the owner of a directory using Python.
Contact Us