Python | os.lchown() method
Last Updated :
11 Oct, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.lchown()
method in Python is used to change the owner and group id of the specified file path to the specified numeric owner id (UID) and group id (GID). This method does not follow symlinks and is equivalent to os.chown(path, uid, gid, follow_symlinks = False)
method.
Note: os.lchown()
method is available only on UNIX platforms and the functionality of this method is typically available only to the superuser or a privileged user.
Syntax: os.lchown(pth, uid, gid)
Parameters:
path: A path-like object representing the he file path for which ownership to be set.
uid: An integer value representing the owner id to be set for the file.
gid: An integer value representing the group id to be set for the file.
Return Type: This method does not return any value.
Code #1: Use of os.lchown() method
import os
path = "./file.txt"
print ( "Owner id of the file:" , os.stat(path).st_uid)
print ( "Group id of the file:" , os.stat(path).st_gid)
uid = 400
gid = 500
os.lchown(path, uid, gid)
print ( "\nOwner and group id of the file changed" )
print ( "\nOwner id of the file:" , os.stat(path).st_uid)
print ( "Group id of the file:" , os.stat(path).st_gid)
|
Output:
Code #2: Use of os.lchown() method to set any one id and leave other unchanged.
import os
path = "./file.txt"
print ( "Owner id of the file:" , os.stat(path).st_uid)
print ( "Group id of the file:" , os.stat(path).st_gid)
uid = 1000
gid = - 1
os.lchown(path, uid, gid)
print ( "\ngroup id of the file changed" )
print ( "\nOwner id of the file:" , os.stat(path).st_uid)
print ( "Group id of the file:" , os.stat(path).st_gid)
|
Output:
Code #3: If the specified path is a symlink
import os
path = "./file.txt"
symlink = "file(symlink).txt"
os.symlink(path, symlink)
print ( "Owner id of the file:" , os.stat(path).st_uid)
print ( "Group id of the file:" , os.stat(path).st_gid)
print ( "Owner id of the symlink:" , os.stat(symlink).st_uid)
print ( "Group id of the symlink:" , os.stat(symlink).st_gid)
uid = 600
gid = 700
os.lchown(symlink, uid, gid)
print ( "\nOwner id and group id changed" )
print ( "\nOwner id of the file:" , os.stat(path).st_uid)
print ( "Group id of the file:" , os.stat(path).st_gid)
print ( "Owner id of the symlink:" , os.stat(symlink).st_uid)
print ( "Group id of the symlink:" , os.stat(symlink).st_gid)
|
Output:
Reference: https://docs.python.org/3/library/os.html
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...