Python os.access() Method
Python 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 the suid/sgid environment.
Syntax
access()The method syntax is as follows:
os.access(path, mode);
Parameters
path-- The path to check for access permissions.
mode-- mode is F_OK, test whether the path exists, 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
Returns True if access is allowed, otherwise returns False.
Example
The following example demonstrates the use of the access() method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
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