Python3 os.access() Method
Python3 OS File/Directory Methods
Overview
The os.access() method uses the current uid/gid to attempt to access the path. Most operations use the effective uid/gid, so the runtime environment can attempt in a suid/sgid environment.
Syntax
access()The syntax of the method is as follows:
os.access(path, mode);
Parameters
path-- The path to be used to check for access permission.
mode-- mode is F_OK, test for the existence of the path, or it can be one or more of R_OK, W_OK, and X_OK.
- os.F_OK:As the mode parameter of access(), test whether the path exists.
- os.R_OK:Included in the mode parameter of access(), test whether the path is readable.
- os.W_OKIncluded in the mode parameter of access(), test whether the path is writable.
- os.X_OKIncluded in the mode parameter of access(), test whether the path is executable.
Return Value
If access is allowed, return True, otherwise return False.
Example
The following example demonstrates the use of the access() method:
#!/usr/bin/python3
import os, sys
# 假定 /tmp/foo.txt 文件存在,并有读写权限
ret = os.access("/tmp/foo.txt", os.F_OK)
print ("F_OK - 返回值 %s"% ret)
ret = os.access("/tmp/foo.txt", os.R_OK)
print ("R_OK - 返回值 %s"% ret)
ret = os.access("/tmp/foo.txt", os.W_OK)
print ("W_OK - 返回值 %s"% ret)
ret = os.access("/tmp/foo.txt", os.X_OK)
print ("X_OK - 返回值 %s"% ret)
The output of the above program is:
F_OK - 返回值 True R_OK - 返回值 True W_OK - 返回值 True X_OK - 返回值 FalseOther Extensions