Latest web development tutorials

Python3 os.access () method

Python3 OS file / directory methods Python3 OS file / directory methods


Outline

os.access () method uses the current uid / gid try to access the path. Most operations use effective uid / gid, so the operating environment can be suid / sgid environment to try.

grammar

access () method syntax is as follows:

os.access(path, mode);

parameter

  • path - to be used to detect whether there is access to the path.

  • mode - mode of F_OK, path testing exist, or it may contain R_OK, W_OK and X_OK or R_OK, W_OK and X_OK one or more.

    • os.F_OK: As access () the mode parameters, test path exists.
    • os.R_OK: included in the access () mode parameter, the test path is readable.
    • os.W_OK included in the access () mode parameter, the test path is readable.
    • os.X_OK included in the access () mode parameter, the test path if the executable.

return value

If you allow access to return True, otherwise False.

Examples

The following example demonstrates access () method of use:

#!/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 above program output is:

F_OK - 返回值 True
R_OK - 返回值 True
W_OK - 返回值 True
X_OK - 返回值 False

Python3 OS file / directory methods Python3 OS file / directory methods