Python os.lchown() Method



The Python lchown() method is used to change the owner ID (UID) and group ID (GID) of a specified file path. To leave one of the IDs unchanged, set it to -1.

The UID and GID are integer values associated with each user and group within the system. Only the superusers are allowed to change these IDs.

Syntax

Following is the syntax for Python lchown() method −

os.lchown(path, uid, gid)

Parameters

The Python lchown() method accepts the following parameters −

  • path − This is the file path for which ownership needs to be set.

  • uid − It specifies Owner ID to be set for the file.

  • gid − This is the Group ID to be set for the file.

Return Value

The Python lchown() method does not return any value.

Example

The following example shows the usage of lchown() method. Here, we are changing both owner ID and group ID of a single file.

#!/usr/bin/python
import os, sys

# Open a file
path = "foo.txt"
fd = os.open( path, os.O_RDWR|os.O_CREAT )

# Close opened file
os.close( fd )

# Setting file owner ID
os.lchown( path, 500, -1)

# Set a file group ID
os.lchown( path, -1, 500)
print ("Ownership Changed Successfully!!")

When we run above program, it produces following result −

Ownership Changed Successfully!!

Example

In the following example, we are changing the owner ID and group ID of multiple files at once using the lchown() method.

import os

# List of file paths
filePaths = ["txtFile.txt", "/home/TP/Python/tmp/new/monthly", "/home/TP/Python/tmp/"]

# setting UID and GID
user_id = 501
group_id = 21

# Changing ownership for each file
for path in filePaths:
   os.lchown(path, user_id, group_id)

print("Ownership successfully changed")

On running the above program, it produces the following output −

Ownership successfully changed
python_files_io.htm
Advertisements