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

17 投票
2 回答
4638 浏览
提问于 2025-04-16 02:11
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 更灵活,因为它可以检查读、写和执行的权限,以及路径是否存在,但这两个实现之间有没有我遗漏的细微差别呢?

2 个回答

3

os.access 是用来检查当前用户是否可以访问某个路径的工具。os.path.exists 则是用来检查这个路径是否真的存在。也就是说,即使路径存在,os.access 也有可能返回 False,表示用户无法访问这个路径。

12

与其试图去避免错误,不如直接捕捉这个错误。因为有很多原因可能导致创建文件夹失败。

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 来检查文件是否存在,因为这个方法更容易记住。

撰写回答