os.chmod method in Python

chmod() Function can be used for changing mode of path to passed numeric mode.
Syntax : os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
Here mode can be a value defined in stat module and by changing mode value permissions of file can be changed.

Common mode values for os.chmod() Function

Mode ValueDescription
stat.S_ISUIDSet user ID on execution
stat.S_ISGIDSet group ID on execution
stat.S_ENFMTRecord locking enforced
stat.S_ISVTXSave test image after execution
stat.S_IREADRead by owner
stat.S_IWRITEWrite by owner
stat.S_IEXECExecute by owner
stat.S_IRWXURead, write and execute by owner
stat.S_IRUSRRead by owner
stat.S_IWUSRWrite by owner
stat.S_IXUSRExecute by owner
stat.S_IRWXGRead, write and execute by group
stat.S_IRGRPRead by group
stat.S_IWGRPWrite by group
stat.S_IXGRPExecute by group
stat.S_IRWXORead, write and execute by others
stat.S_IROTHRead by others
stat.S_IWOTHWrite by others
stat.S_IXOTHExecute by others

Using os.chmod() Function for Changing File Permissions

Example 1

# Python program to explain os.chmod() method 
  
# importing necessary libraries 
import os, sys, stat 
  
# Set given file read by the owner. 
os.chmod("some file", stat.S_IREAD) 
print("File can be read only by owner.") 

Example 2

# Python program to explain os.chmod() method 
  
# importing necessary libraries 
import os, sys, stat 

# Set given file read by others. 
os.chmod("some file", stat.S_IROTH) 
print("File can be read by others") 

Example 3

# Python program to explain os.chmod() method 
  
# importing necessary libraries 
import os, sys, stat 
  
# Set given file written by the owner. 
os.chmod("some file", stat.S_IWRITE)
print("File can be written by owner only")

Example 4

# Python program to explain os.chmod() method 
  
# importing necessary libraries 
import os, sys, stat  
  
# Set given file executed by the owner. 
os.chmod("some file", stat.S_IXUSR) 
print("File can be written and executed only by the owner.")

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

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

Recent Posts