fchmod() function of os module in Python

The fchmod() function of the os module in Python changes the file permissions of a file associated with a file descriptor. The permissions are specified by doing a bitwise OR of one or more permission masks.

Os Updated 30 Mar 2023 1 min read

Function Name

fchmod()

Function Signature

fchmod(fd, mode)

Overview

  • Given a file descriptor, the function fchmod() of os module in Python changes the permissions of the associated file. To change file permissions using only a file path, instead of a file descriptor the os.chmod() function to be used.

Parameters

fd - File descriptor. Note that this is not the file object as returned by the built-in function open(). It has to be a descriptor as returned by the function like os.open().

mode - One or more file permissions bitwise ORed

Return Value

None

Example

python
# Example Python program that changes the permissions

            # for a file through its file descriptor using

            # the os.fchmode() function

            import os

            import stat

# File for which the permissions need to be changed

            fileDescritor    = os.open("/PythonProgs/test.txt", os.O_RDWR)

            filePermissions = stat.S_IRWXU | stat.S_IRGRP | stat.S_IXOTH

# Change the file permissions

            os.fchmod(fileDescritor, filePermissions)

Output

Though the above program does not print anything issuing an ls -l on the test.txt prints the following, that shows the new file permissions for test.txt.

python
mymac:PEX usr1$ ls -l test.txt

            -rwxr----x  1 root  wheel  0 Mar 30 13:59 test.txt