Python—os.access和os.path.access之间是否存在差异?

Python—os.access和os.path.access之间是否存在差异?,python,operating-system,module,Python,Operating System,Module,与: def CreateDirectory(pathName): if not os.access(pathName, os.F_OK): os.makedirs(pathName) 我知道os.access更灵活一些,因为您可以检查RWE属性以及路径是否存在,但这两种实现之间是否存在我在这里遗漏的细微差别?最好只是捕获异常,而不是试图阻止它。makedirs可能失败的原因有无数 def CreateDirectory(pathName): if not os

与:

def CreateDirectory(pathName):
    if not os.access(pathName, os.F_OK):
        os.makedirs(pathName)

我知道os.access更灵活一些,因为您可以检查RWE属性以及路径是否存在,但这两种实现之间是否存在我在这里遗漏的细微差别?

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

def CreateDirectory(pathName):
    if not os.path.exists(pathName):
        os.makedirs(pathName)

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

os.access
测试当前用户是否可以访问路径
os.path.exists
检查路径是否存在
os.access
即使路径存在,也可能返回
False

如果要相信文档,它甚至比答案所说的更微妙。
os.F_OK
模式专门用于测试存在性,而不是权限;而对于
os.path.exists()
:“在某些平台上,如果没有权限对请求的文件执行os.stat(),则此函数可能返回False,即使路径实际存在。”对于测试存在性,say
access
stat
便宜。
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