Python os.access() method
Python OS file/directory methods
Overview
The os.access() method uses the current uid/gid to try to access a path. Most operations use the effective uid/gid, so the runtime environment can attempt this in a suid/sgid environment.
Syntax
The **access()** method syntax is as follows:
os.access(path, mode);
Parameters
-
path -- The path whose access permission is to be checked.
-
mode -- mode is F_OK to test whether the path exists, or it can be one or more of R_OK, W_OK and X_OK.
- os.F_OK: Used as the mode parameter of access() to test whether path exists.
- os.R_OK: Included in the mode parameter of access() to test whether path is readable.
- os.W_OK Included in the mode parameter of access() to test whether path is writable.
- os.X_OK Included in the mode parameter of access() to test whether path is executable.
Return Value
Returns True if access is allowed, otherwise False.
Example
The following example demonstrates the use of the access() method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys
# Assume the file /tmp/foo.txt exists and has read/write permissions
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 - 返回值 False