Python os.fchown() Method



Description

The Python os.fchown() method is used to change the owner and group id of the given file. Only the superuser has permission to modify or perform operations on the file using this method. Therefore, use the "sudo" command while running the code.

The fchown() method accepts three parameters namely fd, uid and gid. The "uid" and "gid" sets the owner and group id to the file specified by "fd" argument. If we want to leave any of the ids unchanged, set it to -1.

Note − This method is available from Python 2.6 onwards. And, can be used on UNIX platform only.

Syntax

Following is the syntax for Python os.fchown() method −

os.fchown(fd, uid, gid);

Parameters

The Python os.fchown() methods accepts the following parameters −

  • fd − This is the file descriptor for which owner id and group id need to be set up.

  • uid − This is Owner ID to be set for the file.

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

Return Value

Python os.fchown() method does not return any value.

Example

The following example shows the usage of fchown() method. Here, we are opening a file in read-only mode and then trying to set the owner and group ID of the file with the help of fchown().

import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
# Set the user Id to 100 for this file.
os.fchown( fd, 100, -1)
# Set the group Id to 50 for this file.
os.fchown( fd, -1, 50)
print("Changed ownership successfully!!")
# Close opened file.
os.close( fd )

When we run above program, it produces following result −

Changed ownership successfully!!

Example

As previously mentioned, only the superusers are allowed to modify the ownership of a given file. In the following example, we are trying to modify the owner ID which will result in PermissionError.

import os
# Open a file
fileObj = os.open("newFile.txt", os.O_RDONLY)
try:
   os.fchown(fileObj, 10,-1)
   print("Ownership changed for the given file.")
except PermissionError:
   print("Don't have permission to change the owner/group id of this file.")
except OSError as e:
   print(f"Error: {e.strerror}")
# Close the file
os.close(fileObj)

On executing the above program, it produces following result −

Don't have permission to change the owner/group id of this file.
python_files_io.htm
Advertisements