11

This is only a question regarding which one would be more "pythonic"

using 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"

or using 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"

As you can see on the examples above, which one would be more correct on python? Also, On which cases should i use try/except instead if/else ? I mean, should i replace all my if/else tests to try/except?

Thanks in advance.

2
  • just a comment, it's not a must but when using except try to catch a specific one...like in your case OSError for the makedirs. Commented Jan 13, 2014 at 15:06
  • You can also look at this post Commented Jan 13, 2014 at 15:17

1 Answer 1

10

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.