How to get the permission mask of a file in Python
Last Updated :
23 Jan, 2024
In UNIX-like operating systems, new files are created with a default set of permissions. We can restrict or provide any specific set of permissions by applying a permission mask. Using Python, we can get or set the file’s permission mask. In this article, we will discuss how to get the permission mask of a file in Python.
Get the Permission Mask of a File in Python
Below is an example by which we can perform changing file permissions in the Python OS Module as well as getting the permission mask of a file in Python. Before moving, firstly we understand the method that we have used in this example:
- os.stat(): This method is used to perform
stat()
system calls on the specified path. This method is used to get the status of the specified path.
Example:
In this example, the os.stat()
function is used to obtain the status of a file named file.txt
. The script then accesses the file’s permission mask from the status. Finally, the permission mask is displayed in octal format using both direct extraction and bitwise operations.
Python3
import os
filename = "./file.txt"
print ( "Status of %s:" % filename)
status = os.stat(filename)
print (status)
print ( "\nFile type and file permission mask:" , status.st_mode)
print ( "File type and file permission mask(in octal):" ,
oct (status.st_mode))
print ( "\nFile permission mask (in octal):" , oct (status.st_mode)[ - 3 :])
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
Shorter Version of the Previous Code
In this example, the script uses os.stat
to fetch the status of file.txt
. The last three digits of the file’s permission mask in octal format using oct() are then extracted and displayed.
Python3
import os
filename = "./file.txt"
mask = oct (os.stat(filename).st_mode)[ - 3 :]
print ( "File permission mask:" , mask)
|
Output
File permission mask: 644
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...