A RetroSearch Logo

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

Search Query:

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

Python os.chmod() Method

Python os.chmod() Method

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

Syntax

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

os.chmod(path, mode);
Parameters Return Value

This method does not return any value.

Example 1

The following example shows the usage of Python os.chmod() 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
# Assuming /tmp/foo.txt exists, Set a file execute by the group.
os.chmod("/tmp/foo.txt", stat.S_IXGRP)
# Set a file write by others.
os.chmod("/tmp/foo.txt", stat.S_IWOTH)
print ("Changed mode successfully!!")

When we run above program, it produces following result −

Changed mode successfully!!
Example 2

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
# Setting the given file written by the group.
os.chmod("Code.txt", stat.S_IWGRP)
print("This file can only be written by the group")
# Setting the given file executed by the group.
os.chmod("Code.txt", 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.chmod() 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
file = "code.txt"
os.chmod(file, 0o755)
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: 0666

os_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