Creation and validation of directory using try/except or if else?
This question already has an answer here:
The second one is more pythonic: "Easier to ask for forgiveness than permission."
But there is another benefit of using exceptions in your particular case. If your application runs multiple processes or threads "asking permissions" doesn't guarantee consistency. For example following code runs well in single thread, but may be crashed in multiple ones:
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)
链接地址: http://www.djcxy.com/p/9268.html
上一篇: 用给定的路径创建一个新的文件夹