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属性和路径是否存在,但是这两种实现之间有什么细微的区别吗?
发布于 2010-08-02 21:38:46
最好只是捕捉异常,而不是试图阻止它。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
来测试文件是否存在,因为它更容易记忆。
发布于 2010-08-02 21:41:00
os.access
会测试当前用户是否可以访问该路径,os.path.exists
会检查该路径是否存在。即使路径存在,os.access
也可能返回False
。
https://stackoverflow.com/questions/3388223
复制相似问题