-2

Which method or checking conditions is more suggested to use:

import os

# method 1
if not os.path.exists("somedir"):
    os.makedirs("somedir")

# method 2
try:
    assert not os.path.exists("somedir")
except AssertionError:
    pass
else:
    os.makedirs("somedir")

# method 3
try:
    os.makedirs("somedir")
except OSError:
    pass

Would method 3 still break The Zen of Python ("Errors should never pass silently." if there was some logging?

Kuba Chrabański
  • 625
  • 2
  • 7
  • 17
  • 1
    Use `os.makedirs("somedir", exist_ok=True)`. – 9769953 Sep 27 '18 at 18:08
  • It's not an answer to the question as this os.makedirs() was just an example but thank you I didn't know about this option ;) – Kuba Chrabański Sep 27 '18 at 18:10
  • 1
    `assert` is typically associated with a debugging scenario: alluded to in [the docs](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement) and [other resources](https://stackoverflow.com/a/41721518/2823755) using the search terms "python assert usage" – wwii Sep 27 '18 at 18:42

1 Answers1

1

Method 3 is, in general, superior. The other methods introduce a race condition, where another process could create the directory after you test for its existence but before you actually try to create it.

As pointed out in a comment, the exist_ok option does this for you, by simply not raising an exception if the exception is caused by a pre-existing directory (while still raising an exception for other errors).

chepner
  • 497,756
  • 71
  • 530
  • 681