【发布时间】: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 时尝试捕捉一个特定的......就像你的情况
OSError为makedirs。 -
你也可以看看这个post
标签: python python-2.7