2010-08-02 144 views
17
def CreateDirectory(pathName): 
    if not os.access(pathName, os.F_OK): 
     os.makedirs(pathName) 

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

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

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

+3

如果文档是可信的,它比答案所说的更加微妙。 'os.F_OK'模式专门用于测试是否存在,而不是权限;而对于'os.path.exists()':“在某些平台上,如果在所请求的文件上没有授予权限来执行os.stat(),则该函数可能返回False,即使路径物理上存在。 [FreeBSD手册页](http://www.freebsd.org/cgi/man.cgi?query=access&sektion=2)表示'access'比'stat'更便宜。 – 2012-10-08 19:15:03

回答

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 

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

4

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