Python3 os.access() Method
Python3 OS File/Directory Methods
Overview
The os.access()
method attempts to access a path using the current uid/gid. Most operations use the effective uid/gid, so the runtime environment can attempt in suid/sgid environment.
Syntax
The syntax for the access() method is as follows:
os.access(path, mode);
Parameters
path -- The path to be tested for access permissions.
mode --
mode
can beF_OK
to test the existence of the path, or it can includeR_OK
,W_OK
, andX_OK
or any combination thereof.os.F_OK: Used as the
mode
parameter foraccess()
, tests ifpath
exists.os.R_OK: Included in the
mode
parameter foraccess()
, tests ifpath
is readable.os.W_OK: Included in the
mode
parameter foraccess()
, tests ifpath
is writable.os.X_OK: Included in the
mode
parameter foraccess()
, tests ifpath
is executable.
Return Value
Returns True
if access is allowed, otherwise returns False
.
Example
The following example demonstrates the use of the access()
method:
#!/usr/bin/python3
import os, sys
# Assuming /tmp/foo.txt exists and has read/write permissions
ret = os.access("/tmp/foo.txt", os.F_OK)
print("F_OK - Return value %s" % ret)
ret = os.access("/tmp/foo.txt", os.R_OK)
print("R_OK - Return value %s" % ret)
ret = os.access("/tmp/foo.txt", os.W_OK)
print("W_OK - Return value %s" % ret)
ret = os.access("/tmp/foo.txt", os.X_OK)
print("X_OK - Return value %s" % ret)
Executing the above program outputs:
F_OK - Return value True
R_OK - Return value True
W_OK - Return value True
X_OK - Return value False