这只是一个关于哪一个更"pythonic"的问题
使用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"
Run Code Online (Sandbox Code Playgroud)
或使用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"
Run Code Online (Sandbox Code Playgroud)
正如你在上面的例子中看到的那样,哪一个在python上会更正确?另外,在哪些情况下我应该使用try/except而不是if/else?我的意思是,我应该替换所有我的if/else测试来尝试/除外吗?
提前致谢.
第二个是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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1019 次 |
| 最近记录: |