7

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.

thclpr
  • 4,945
  • 7
  • 39
  • 79
  • 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`. – Kobi K Jan 13 '14 at 15:06
  • You can also look at this [post](http://stackoverflow.com/a/7604717/1982962) – Kobi K Jan 13 '14 at 15:17

1 Answers1

7

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) 
Dmitry Vakhrushev
  • 1,322
  • 7
  • 11