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

标签 python operating-system module

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 属性以及路径是否存在,但是这两种实现之间是否存在一些细微差别?

最佳答案

最好只捕获异常而不是试图阻止它。 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 来测试文件是否存在,因为它更容易记住。

关于Python - os.access 和 os.path.exists 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3388223/

相关文章:

python - 如何在类型提示中指定 pandas 系列元素的类型?

python - 为什么 id( )'s result on IronPython equal to id()' s 在 Python 上没有结果?

swift - 获取 NSRunningApplication 的 ProcessInfo

php - joomla 2.5 模块中的图像插入字段

module - 如何从私有(private)模块中的公共(public)函数引用私有(private)类型?

javascript - 我可以自行访问模块导出实例吗?

python - 用numpy找出矩阵是否是正定的

python - 从请求导入 PandaRequest ImportError : No module named 'request'

linux - 操作系统内核是否以与 IPC 相同的方式与进程通信?

python - 是否可以使用 Python 创建操作系统?