Python 3 – os.fchmod() Method

Python 3 – os.fchmod() Method

Description

The fchmod() method changes the mode of the given file descriptor fd to a numeric mode. The mode can take the following values or a bitwise OR combination of these values:

Note – This method is available in Python 2.6 and above.

  • stat.S_ISUID – Sets the user ID at execution time.
  • stat.S_ISGID – Sets group ID on execution.

  • stat.S_ENFMT – Forces record locking.

  • stat.S_ISVTX – Saves text image after execution.

  • stat.S_IREAD – Read by owner.

  • stat.S_IWRITE – Write by owner.

  • stat.S_IEXEC – Execute by owner.

  • stat.S_IRWXU – Read, write, and execute by owner.

  • stat.S_IRUSR – Read by owner.

  • stat.S_IWUSR – Write by owner.

  • stat.S_IXUSR – Execute by owner.

  • stat.S_IRWXG – Read, write, and execute by group.

  • stat.S_IRGRP – Read by group.

  • stat.S_IWGRP – Write by group.

  • stat.S_IXGRP – Execute by group.

  • stat.S_IRWXO – Read, write, and execute by others.

  • stat.S_IROTH – Read by others.

  • stat.S_IWOTH – Write by others.

  • stat.S_IXOTH – Execute by others.

Syntax

Following is the syntax of the fchmod() method –

os.fchmod(fd, mode)

Parameters

  • fd – This is the file descriptor whose mode is to be set.
  • mode – This can take any of the above mentioned values or a bitwise OR combination of them.

Return Value

This method does not return any value. Available only on Unix-like operating systems.

Example

The following example shows the usage of the fchmod() method –

#!/usr/bin/python3
import os, sys, stat

# Now open a file "/tmp/foo.txt"
fd = os.open("/tmp",os.O_RDONLY)

# Set a file to be executable by the group.
os.fchmod(fd, stat.S_IXGRP)

# Set a file to be writable by others.
os.fchmod(fd, stat.S_IWOTH)

print ("Mode changed successfully!!")

# Close the open file.
os.close( fd )

Result

When we run the above program, it will produce the following output –

Successful mode change!!

Leave a Reply

Your email address will not be published. Required fields are marked *