Python os.umask() Method

Python os.umask() Method

  1. Syntax of os.umask() Method
  2. Example 1: Use the os.umask() Method in Python
  3. Example 2: Use Octal Representation in the os.umask() Method
  4. Example 3: Find the Permissions in the Current Working Directory Using the os.umask() Method

Python os.umask() method is an efficient way to assign the present numeric umask value and retrieve the previous umask value. Umask determines the file permissions for any newly created folders or files.

Syntax of os.umask() Method

os.umask(mask)

Parameters

mask - an integer number representing a valid umask value.

Return

This method returns an integer value representing the previous umask value.

Example 1: Use the os.umask() Method in Python

import os

current_mask = 18

previous_umask = os.umask(current_mask)

print("The current umask value is:", current_mask)

print("The previous umask value is:", previous_umask)

Output:

The current umask value is: 18
The previous umask value is: 18

Note that the input parameter of os.umask() can be either integer or an octal value. In the above example, 18 in decimal is equivalent to 0o022 in octal representation.

Example 2: Use Octal Representation in the os.umask() Method

import os

current_mask = 0o777

previous_umask = os.umask(current_mask)

print("The current umask value is:", current_mask)

print("The previous umask value is:", previous_umask)

Output:

The current umask value is: 511
The previous umask value is: 18

Note that the return value of os.umask() will always be an integer even if you enter an octal value as a parameter.

Example 3: Find the Permissions in the Current Working Directory Using the os.umask() Method

import os

previous_mask = os.umask(0o55)

os.system("ls -alh > test")

os.umask(previous_mask)

The above code doesn’t display output but opens a new file called test in the terminal. That file shows the record of all the files in the current working directory, such as file size, permissions, file creation date, etc.

umask

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method