os.access(path, mode)
tests for access to the path.It uses either UID or GID.
os.access(path, mode)
has two input parameters, path and mode.
- For the
path
parameter : we can pass any string representing the path as an argument. - For the
mode
parameter, we can only pass any one of supported modes.
os.access Syntax
os.access(path, mode)
os.access Parameters
path
– The path to use to check for access.mode
– F_OK is used to test whether the specified path exists. It can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions. Following values can be passed as the mode parameter ofos.access
- os.F_OK: whether the specified path exists.
- os.R_OK: whether the specified path readable.
- os.W_OK: whether the specified path writable.
- os.X_OK: whether the specified path can be executed.
os.access returns
True if access is allowed, else returns False.
Demo #1: Understand os.access() method
The following example demonstrates the use of the access() method:
#!/usr/bin/python3
import os
# Assume that the /root/apidemos.com.txt file exists and has read and write permissions
print("F_OK - return %s"% os.access("/root/apidemos.com.txt", os.F_OK))
print("R_OK - return %s"% os.access("/root/apidemos.com.txt", os.R_OK))
print("W_OK - return %s"% os.access("/root/apidemos.com.txt", os.W_OK))
print("X_OK - return %s"% os.access("/root/apidemos.com.txt", os.X_OK))
print("F_OK | R_OK | W_OK - return %s"% os.access("/root/apidemos.com.txt", os.F_OK | os.R_OK | os.W_OK))
Output:
Demo #2: open a file only validating access is allowed
The following example demonstrates open a file only validating access is allowed:
#!/usr/bin/python3
import os
def read_file_content(file_path):
if os.access(file_path, os.R_OK):
with open(file_path) as fp:
return fp.read()
return file_path + " can not read, return default data here!!!"
print(read_file_content("/root/apidemos.com.txt"))
Output: