Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

10
  • 18
    This answer covers pretty much every special case as far as I can tell. I plan on wrapping this in a "if not os.path.isdir()" though since I expect the directory to exist almost every time and I can avoid the exception that way. Commented Apr 26, 2013 at 5:52
  • 7
    @CharlesL. An exception is probably cheaper than the disk IO of the check, if your reason is performance. Commented Apr 29, 2014 at 22:39
  • 2
    @jpmc26 but makedirs does additional stat, umask, lstat when only checking to throw OSError. Commented Sep 19, 2014 at 10:31
  • 6
    This is the wrong answer, as it introduces a potential FS race cond. See answer from Aaron Hall. Commented Jan 8, 2016 at 15:20
  • 6
    as @sleepycal has said, this suffers from a similar race condition as the accepted answer. If between raising the error and checking os.path.isdir someone else deletes the folder, you will raise the wrong, outdated, and confusing error that folder exists. Commented Apr 27, 2016 at 7:20