Python os.access() Method Example
Below are some examples by which we can understand how to determine if a file is readable using os.R_OK in Python and how to verify if a file is writable with os.W_OK in Python:
Checking File Access Permission Using os.access()
In this example, the code uses the os.access()
function to check different access permissions for a file named “gfg.txt”. It checks the file’s existence (os.F_OK
), read permission (os.R_OK
), write permission (os.W_OK
), and execution permission (os.X_OK
).
Python3
# importing all necessary libraries import os import sys # Checking access with os.F_OK path1 = os.access( "gfg.txt" , os.F_OK) print ( "Exists the path:" , path1) # Checking access with os.R_OK path2 = os.access( "gfg.txt" , os.R_OK) print ( "Access to read the file:" , path2) # Checking access with os.W_OK path3 = os.access( "gfg.txt" , os.W_OK) print ( "Access to write the file:" , path3) # Checking access with os.X_OK path4 = os.access( "gfg.txt" , os.X_OK) print ( "Check if path can be executed:" , path4) |
Output:
Exists the path: True
Access to read the file: True
Access to write the file: False
Check if path can be executed: False
Open a File and Validating Access Using os.access() Function
In this example, the code checks if the file “gfg.txt” has read (`os.R_OK`) access. If readable, it opens the file and returns its content using a with statement to automatically handle file closure. If the file is not readable, it returns the string “Facing some issue.”
Python3
# checking readability of the path if os.access( "gfg.txt" , os.R_OK): # open txt file as file with open ( "gfg.txt" ) as file : return file .read() # in case can't access the file return "Facing some issue" |
Output:
Facing some issue
Python | os.access() Method
os.access() method uses the real uid/gid to test for access to the path. Most operations use the effective uid/gid, therefore, this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to the path. In this article, we will learn about the access() function of the OS module in Python.