【问题标题】:Python - difference between os.access and os.path.exists?Python - os.access 和 os.path.exists 之间的区别?
【发布时间】:2011-03-24 05:25:45
【问题描述】:
def CreateDirectory(pathName):
    if not os.access(pathName, os.F_OK):
        os.makedirs(pathName)

对比:

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

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

【问题讨论】:

  • 如果要相信文档,它甚至比答案所说的更微妙。 os.F_OK 模式专门用于测试存在性,而不是权限;而对于os.path.exists():“在某些平台上,如果未授予对请求的文件执行 os.stat() 的权限,即使路径物理存在,此函数也可能返回 False。” FreeBSD man pagesaccessstat 便宜用于测试存在性。

标签: python operating-system module


【解决方案1】:

最好只捕获异常而不是试图阻止它。 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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2021-06-10
      • 2021-01-02
      • 2016-03-26
      • 2014-01-03
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多