Workflow to create a folder if it doesn't exist already


In this interesting thread, the users give some options to create a directory if it doesn’t exist.

The answer with most votes it’s obviously the most popular, I guess because its the shortest way:

if not os.path.exists(directory):

The function included in the 2nd answer seems more robust, and in my opinion the best way to do it.

import os
import errno

def make_sure_path_exists(path):
    except OSError as exception:
        if exception.errno != errno.EEXIST:

So I was wondering, what does people do in their scripts? Type 2 lines just to create a folder? Or even worst, copy, and paste the function make_sure_path_exists in every script that needs to create a folder?

I’d expect that such a wide spread programming language as Python would already have a library with includes a similar function.

The other 2 programming languages that I know, which are more like scripting languages, can do this with ease.

Bash: mkdir -p path

Powershell: New-Item -Force path

Please don’t take this question as a rant against Python, because it’s not intended to be like that.

I’m planing to learn Python to write scripts where 90% of the time I’ll have to create folders, and I’d like to know what is the most productive way to do so.

I really think I’m missing something about Python.


make a module with make_sure_path_exists defined in it. import it when needed.

Answered By – scytale

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published