这只是一个关于哪个会更“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吗?在
提前谢谢。在
第二个更像Python:“请求宽恕比允许更容易。”
但是在特定情况下使用异常还有另一个好处。如果应用程序运行多个进程或线程,“请求权限”不能保证一致性。例如,以下代码在单个线程中运行良好,但在多个线程中可能会崩溃:
相关问题 更多 >
编程相关推荐