Python - os.access和os.path.exists之间的区别?

use*_*896 17 python operating-system module

def CreateDirectory(pathName):
    if not os.access(pathName, os.F_OK):
        os.makedirs(pathName)
Run Code Online (Sandbox Code Playgroud)

与:

def CreateDirectory(pathName):
    if not os.path.exists(pathName):
        os.makedirs(pathName)
Run Code Online (Sandbox Code Playgroud)

我知道os.access有点灵活,因为你可以检查RWE属性以及路径存在,但是这两个实现之间是否存在一些细微差别?

Joh*_*ooy 13

最好只是捕获异常,而不是试图阻止它.makedirs可能失败的原因有很多

def CreateDirectory(pathName):
    try:
        os.makedirs(pathName)
    except OSError, e:
        # could be that the directory already exists
        # could be permission error
        # could be file system is full
        # look at e.errno to determine what went wrong
Run Code Online (Sandbox Code Playgroud)

要回答您的问题,os.access可以测试读取或写入文件的权限(作为登录用户).os.path.exists只是告诉你是否有东西.我希望大多数人会用它os.path.exists来测试文件的存在,因为它更容易记住.