How to Change the Owner of a Directory Using Python
Last Updated :
08 Apr, 2024
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.
Change the Owner of a Directory Using Python
Below are the ways by which we can change the owner of a directory using Python:
- Using os.chown() Method
- Using shutil.chown() Method
Using os.chown() Method
To change the owner and group ID of the given path to the specified numeric owner ID (UID) and group ID (GID), use Python's os.chown() method.
Syntax of os.chown() Method
os.chown(filepath, uid, gid, *, dir_fd = None, follow_symlinks = True)
Parameters:
- path: A file descriptor representing the file whose uid and gid is to be set
- uid: An integer value representing the owner id to be set for the path.
- gid: An integer value representing the group id to be set for the path. To leave any one of the ids unchanged, set it to -1.
- dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
- follow_symlinks (optional): The default value of this parameter is True. If we do not want os.chown() method to follow symlink, we can set it to False. If it is False, method will operate on the symbolic link itself instead of the file the link points to.he procedure will work on the symbolic link rather than the file it links to.
Return Type: This method does not return any value.
Example 1: Changing Owner and Group ID
In this example, the function change
is defined to modify the owner and group IDs of a specified file path (path
). It prints the current owner and group IDs, changes them to the provided uid
and gid
, then displays the updated IDs.
Python3
import os
def change(path, uid, gid):
try:
# Displaying current owner and group IDs
print("File's owner id:", os.stat(path).st_uid)
print("File's group id:", os.stat(path).st_gid)
# Changing the owner id and group id of the file
os.chown(path, uid, gid)
print("\nOwner id and group id of the file have been changed successfully")
# Displaying updated owner and group IDs
print("\nFile's owner id now is:", os.stat(path).st_uid)
print("File's group id now is:", os.stat(path).st_gid)
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 = 1500
gid = 1500
change(path, uid, gid)
Output:
└─$ sudo python3 kislay.py
file's owner id: 100
file's group id: 100
Owner id and group id of the file is changed successfully
file's owner id now is: 1500
file's group id now is: 1500
Example 2: Changing Owner ID Only
In this example, the function change_owner
is utilized to update the owner ID of a specified file (path
) while maintaining the existing group ID. It first prints the current owner and group IDs, then changes the owner ID to the provided uid
, and finally displays the updated owner and group IDs.
Python3
import os
def change_owner(path, uid):
try:
# Printing the current owner id and group id
print("File's owner id:", os.stat(path).st_uid)
print("File's group id:", os.stat(path).st_gid)
# Setting gid as -1 to leave the group id unchanged
gid = -1
os.chown(path, uid, gid)
print("\nOwner id of the file has been changed successfully, leaving the group id unchanged")
# Printing the owner id and group id of the file now
print("\nFile's owner id now is:", os.stat(path).st_uid)
print("File's group id now is:", os.stat(path).st_gid)
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 = 200
change_owner(path, uid)
Output:
└─$ sudo python3 kislay.py
[sudo] password for kislay:
file's owner id: 1500
file's group id: 1000
Owner id of the file is changed successfully leaving the group id unchanged
file's owner id now is: 200
file's group id now is: 1000
Using shutil.chown() Method
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()
.
Python3
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
Similar Reads
How To Detect File Changes Using Python
In the digital age, monitoring file changes is essential for various applications, ranging from data synchronization to security. Python offers robust libraries and methods to detect file modifications efficiently. In this article, we will see some generally used method which is used to detect chang
3 min read
Delete a directory or file using Python
In this article, we will cover how to delete (remove) files and directories in Python. Python provides different methods and functions for removing files and directories. One can remove the file according to their need. Table of Content Using the os.remove() MethodDelete a FileRemove file with absol
6 min read
Python Program to Safely Create a Nested Directory
Creating a nested directory in Python involves ensuring that the directory is created safely, without overwriting existing directories or causing errors. To create a nested directory we can use methods like os.makedirs(), os.path.exists(), and Path.mkdir(). In this article, we will study how to safe
2 min read
Python Loop through Folders and Files in Directory
File iteration is a crucial process of working with files in Python. The process of accessing and processing each item in any collection is called File iteration in Python, which involves looping through a folder and perform operation on each file. In this article, we will see how we can iterate ove
4 min read
Rename all file names in your directory using Python
Given multiple files in a directory having different names, the task is to rename all those files in sorted order. We can use OS module in order to do this operation. The OS module in Python provides functions for interacting with the operating system and provides a portable way of using operating s
1 min read
How to get the permission mask of a file in Python
In UNIX-like operating systems, new files are created with a default set of permissions. We can restrict or provide any specific set of permissions by applying a permission mask. Using Python, we can get or set the file's permission mask. In this article, we will discuss how to get the permission ma
2 min read
Python program to modify the content of a Binary File
Given a binary file that contains some sentences (space separated words), let's write a Python program to modify or alter any particular word of the sentence. Approach:Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable âposâ stores the position of fi
2 min read
How Use Linux Command In Python Using System.Os
Using the system module from the os library in Python allows you to interact with the Linux command line directly from your Python script. This module provides a way to execute system commands, enabling you to automate various tasks by integrating Linux commands seamlessly into your Python code. Whe
3 min read
Create a watchdog in Python to look for filesystem changes
Many times a file is needed to be processed at the time of its creation or its modification. This can be done by following changes in a particular directory. There are many ways in python to follow changes made in a directory. One such way is to use the watchdog module. As the name suggests this mod
4 min read
How To Copy Files From One Server To Another in Python
Copying files between servers can seem daunting, but with Python, it becomes a straightforward process. Python provides several libraries to handle file transfers, with paramiko being a popular choice because it allows for SSH connections and file transfers via SFTP (SSH File Transfer Protocol). In
3 min read