Python os.access() Method

The os.access() method in Python uses the real uid/gid to check access to the path. It checks if the invoking user has specific access rights to a given path (file or directory).

This method is particularly notable in setuid/setgid (suid/sgid) environments.

This method, by using the real UID/GID, helps in determining what the original invoking user can access, as opposed to what the program (with its elevated privileges) can access.

Syntax

os.access(path, mode, dir_fd, effective_ids, follow_symlinks)

Parameters

Name Description
path (Required) It is a file or directory path to be tested for access
mode (Required) os.F_OK: It checks if the path exists.
os.R_OK: It checks if the path is readable.
os.W_OK: It checks if the path is writable.
os.X_OK: It checks if the path is executable.
dir_fd (Optional) If NONE, the path will be relative to the directory
effective_ids (Optional) If TRUE, this method will use effective uid/gid instead of the real uid/gid
follow_symlinks (Optional) If TRUE, this method will follow the symbolic link instead of the file the link points to.

Return value

It returns True if access is allowed, False otherwise.

Visual representation

Figure of Python os.access() Method

Example 1: Checking file access permission

We will check the existence and permission of the “new.txt” file:

Screenshot of file before using os.access()

import os

# Checking access with os.F_OK
new_file_perm1 = os.access("new.txt", os.F_OK)
print("Does the path exists:", new_file_perm1)

# Checking access with os.R_OK
new_file_perm2 = os.access("new.txt", os.R_OK)
print("Do I have an access to read the file:", new_file_perm2)

# Checking access with os.W_OK
new_file_perm3 = os.access("new.txt", os.W_OK)
print("Do I have an access to write to file:", new_file_perm3)

# Checking access with os.X_OK
new_file_perm4 = os.access("new.txt", os.X_OK)
print("Can it be executed:", new_file_perm4)

Output

Does the path exists: True
Do I have an access to read the file: True
Do I have an access to write to file: True
Can it be executed: False

Example 2: Checking read and write access

import os

file_path = 'new.txt'

if os.access(file_path, os.R_OK | os.W_OK):
  print(f"Read and write access to '{file_path}' is allowed.")
else:
  print(f"No read and write access to '{file_path}'.")

Output

Read and write access to 'new.txt' is allowed.

Example 3: Check executable access

Here is the script.sh file we will check:

Checking if executable script .sh file using os.access() function

import os

file_path = 'script.sh'

if os.access(file_path, os.X_OK):
  print(f"The file '{file_path}' is executable.")
else:
  print(f"The file '{file_path}' is not executable.")

Output

The file 'script.sh' is not executable.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.