A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/os_fchmod.htm below:

Python os.fchmod() Method

Python os.fchmod() Method

The Python os.fchmod() method changes the mode of the file to the specified numeric mode. The mode may take one of the following values or bitwise OR combinations of them −

Note − This method is available in Python 2.6 onwards. And only available in UNIX/LINUX platforms.
Syntax

Following is the syntax of Python os.fchmod() method −

os.fchmod(fd, mode);
Parameters Return Value

This method does not return any value.

Example 1

The following example shows the usage of Python os.fchmod() method. Here we are first setting the file to be executed only by the group by passing stat.S_IXGRP as the mode argument to the method. Then we are passing stat.S_IWOTH as the mode argument to the method. This specifies that the file can only be written by others−

import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
# Set a file execute by the group.
os.fchmod( fd, stat.S_IXGRP)
# Set a file write by others.
os.fchmod(fd, stat.S_IWOTH)
print ("Changed mode successfully!!")
# Close opened file.
os.close(fd)

When we run above program, it produces following result −

Changed mode successfully!!
Example 2

In here, we are first setting the file to be written only by the group. This is done by passing stat.S_IWGRP as the mode argument to the method. Then we are passing stat.S_IXGRP as the mode argument to the method. This specifies that the file can only be executed by the group.

# importing the libraries
import os
import sys
import stat
# Now open a file "code.txt"
filedesc = os.open("code.txt", os.O_RDONLY )
# Setting the given file written by the group.
os.fchmod(filedesc, stat.S_IWGRP)
print("This file can only be written by the group")
# Setting the given file executed by the group.
os.fchmod(filedesc, stat.S_IXGRP)
print("Now the file can only be executed by the group.")

While executing the above code we get the following output −

This file can only be written by the group
Now the file can only be executed by the group.
Example 3

Here, when we use the os.fchmod() method, we are writing 0o before setting the permissions. It represents an octal integer. The file permission is set to 755, which means that the owner can read, write and search; others and group can only search in the file.

import os
import stat
file = "code.txt"
filedesc = os.open("code.txt", os.O_RDONLY )
mode = 0o755
os.fchmod(filedesc,mode)
stat = os.stat(file)
mode = oct(stat.st_mode)[-4:]
print('The mode is:',mode)

Following is an output of the above code −

The mode is: 0755

python_file_methods.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4