【问题标题】:Creation and validation of directory using try/except or if else? [duplicate]使用 try/except 或 if else 创建和验证目录? [复制]
【发布时间】:2014-02-01 09:16:30
【问题描述】:

这只是一个关于哪个更“pythonic”的问题

使用如果:

import os
somepath = 'c:\\somedir'
filepath = '%s\\thefile.txt' % somepath
if not os.path.exists(somepath) and not os.path.isfile(filepath):
    os.makedirs(somepath)
    open(filepath, 'a').close
else:
   print "file and dir allready exists"

或使用try/Except:

import os
somepath = 'c:\\somedir'
filepath = '%s\\thefile.txt' % somepath
try:
    os.makedirs(somepath)
except:
    print "dir allready exists"
try:
    with open(filepath):
        // do something
except:
    print "file doens't exist"

正如您在上面的示例中看到的,哪一个在 python 上更正确?另外,在哪些情况下我应该使用 try/except 代替 if/else ?我的意思是,我应该将所有 if/else 测试替换为 try/except 吗?

提前致谢。

【问题讨论】:

  • 只是一个评论,这不是必须的,但是当使用 except 时尝试捕捉一个特定的......就像你的情况 OSErrormakedirs
  • 你也可以看看这个post

标签: python python-2.7


【解决方案1】:

第二个更pythonic:“请求原谅比请求许可更容易。”

但在您的特定情况下使用异常还有另一个好处。如果您的应用程序运行多个进程或线程“请求权限”并不能保证一致性。例如以下代码在单线程中运行良好,但在多个线程中可能会崩溃:

if not os.path.exists(somepath):
    # if here current thread is stopped and the same dir is created in other thread
    # the next line will raise an exception
    os.makedirs(somepath) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    相关资源
    最近更新 更多