使用try/except或if-else创建和验证目录?

2024-06-28 19:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

使用if:

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:

^{pr2}$

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

提前谢谢。在


Tags: andpathimporttxtifosexistsnot
1条回答
网友
1楼 · 发布于 2024-06-28 19:36:21

第二个更像Python:“请求宽恕比允许更容易。”

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

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) 

相关问题 更多 >