On UNIX-like operating systems, new files are created with a default set of permissions. We can restrict or grant any specific or set of permissions by applying a permission mask. Using Python, we can get or set the permission mask for a file.
In this article, we will discuss how to get the permission mask for a file in Python.
Method used -
os.stat () : This method is used to performs stat ()
system call on the specified path. This method is used to get status of the specified path.
Below is a Python program to get a mask of file permissions.
# Python program to get a mask of file permissions # of this file # Import the os module import os # File filename = "./ file.txt" # Now get the file status # using the os.st method at () print ( "Status of% s: " % filename) status = os.stat (filename) # os.stat () method will return # stat_result & # 39; object class & # 39; os.stat_result & # 39; # which will represent # file status. print (status) # st_mode attribute # returned an object & # 39; stat_result & # 39; # will represent the file type and # file mode bits (permissions). print ( "File type and file permission mask:" , status.st_mode) # st_mode attribute is an integer value # but we are interested in an octal value # for file permission mask # So we will change integer value # octal value print ( "File type and file permission mask (in octal):" , oct (status.st_mode)) # last 3 octal digits # represents the file permission mask # and the top indicates the file type # to get the file permission # extract the last 3 octal digits # of status.st_mode co de> print ( "File permission mask (in octal ): " , oct (status.st_mode) [ - 3 :]) # Alternative way print ( "File permission mask (in octal):" , oct (status.st_mode & amp; 0o777 )) |
Exit:
Status of ./file.txt: os.stat_result (st_mode = 33188, st_ino = 801303, st_dev = 2056, st_nlink = 1, st_uid = 1000, st_gid = 1000, st_size = 409, st_atime = 1561590918, st_mtime = 1561590910, st_ctime = 1561590910) File type and file permission mask: 33188 File type and file permission mask (in octal): 0o100644 File permission mask ( in octal): 644 File permission mask (in octal): 0o644
Below is a short version of the above program —
# Python program to get a mask of file permissions # of this file # Import the os module import os c ode> # File filename = "./ file.txt" # Get the file permission mask # of the specified file mask = oct (os.stat (filename) .st_mode) [ - 3 :] # Print mask print ( "File permission mask:" , mask) |
Output:
File permission mask: 644