Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to get the permission mask of a file in Python

How to get the permission mask of a file in Python

Prerequisite: Python | os.umask() method

In UNIX-like operating systems, new files are created with a default set of permissions. We can restrict or provide any specific or set of permissions by applying a permission mask. Using Python, we can get or set file’s permission mask.

In this article, we will discuss about how to get the permission mask of 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 the Python program to get a file’s permission mask –




# Python program to get file permission mask
# of a given file
  
# Import os module
import os
  
# File
filename = "./file.txt"
  
  
# Now get the status of the file
# using os.stat() method
print("Status of %s:" %filename)
status = os.stat(filename)
  
# os.stat() method will return a
# stat_result’ object of ‘os.stat_result’ class
# which will represent 
# the status of file.
print(status)
  
# st_mode attribute of
# returned 'stat_result' object
# will represent the file type and
# file mode bits (permissions).
print("\nFile type and file permission mask:", status.st_mode)
  
  
# st_mode attribute is an integer value
# but we are interested in octal value
# for file's permission mask
  
# So we will change the integer value
# to octal value
print("File type and file permission mask(in octal):",
                                  oct(status.st_mode))
  
# last 3 octal digit 
# represents the file permission mask
# and upper parts tells the file type 
# so to get the file's permission 
# we will extract last 3 octal digit
# of status.st_mode
print("\nFile permission mask (in octal):", oct(status.st_mode)[-3:])
  
# Alternate way
print("File permission mask (in octal):", oct(status.st_mode & 0o777))


Output:

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 program is the short version of above program –




# Python program to get file permission mask
# of a given file
  
# Import os module
import os
  
# File
filename = "./file.txt"
  
# Get the file permission mask
# of the specified file
mask = oct(os.stat(filename).st_mode)[-3:]
  
# Print the mask
print("File permission mask:", mask)


Output:

File permission mask: 644
RELATED ARTICLES

Most Popular

Recent Comments