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

In this interesting threat, 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):
    os.makedirs(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):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

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.



Solution 1:[1]

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

Solution 2:[2]

you can use the below

# file handler
import os
filename = "./logs/mylog.log"
os.makedirs(os.path.dirname(filename), exist_ok=True)

Solution 3:[3]

Getting help from different answers I produced this code

if not os.path.exists(os.getcwd() + '/' + folderName):
    os.makedirs(os.getcwd() + '/' + folderName, exist_ok=True) 

Solution 4:[4]

import os

def main():
    dirName = 'C:/SANAL'

    # Create target directory & all intermediate directories if don't exists
    try:
        os.makedirs(dirName)    
        print("Directory " , dirName ,  " Created ")
    except FileExistsError:
        print("Directory " , dirName ,  " already exists")  

if __name__ == '__main__':
    main()

f = open('C:/SANAL/merhabadünya.txt','w')
for i in range (10):
        f.write('MERHABA %d\r\n' % (i+1))

f.close()

f = open('C:/SANAL/merhabadünya.txt','r')
message = f.read()
print(message)

f.close()       

Solution 5:[5]

None of the current answers provide a clear explanation on how to make os.makedirs idempotent and many are superfluous. Here’s a clear answer with minimal examples:

Python 3

We simply set the exists_ok flag to True.

A Working Example

import os

directory = “my/test/directory/”

os.makedirs(directory, exists_ok = True)

Python 2

We can manually handle it. One way to do this is to check whether the directory already exists using a conditional:

A Working Example

import os

directory = “my/test/directory/”

if not os.path.exists(directory):
    os.makedirs(directory)

Running each working example, you should get no error after multiple executions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 scytale
Solution 2 Rajesh Selvaraj
Solution 3 ASAD HAMEED
Solution 4 Karl
Solution 5