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/