16

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):
    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.

M Somerville
  • 4,499
  • 30
  • 38
RafaelGP
  • 1,749
  • 6
  • 20
  • 35
  • 15
    In Python 3, `os.makedirs()` has a kwarg "exist_ok". See here: https://github.com/python/cpython/blob/master/Lib/os.py#L216 – derricw Aug 20 '15 at 16:31

5 Answers5

20

you can use the below

# file handler
import os
filename = "./logs/mylog.log"
os.makedirs(os.path.dirname(filename), exist_ok=True)
Rajesh Selvaraj
  • 311
  • 3
  • 4
  • The answer is correct, but please make sure if similar answers already exist. In this case, a mention about "exist_ok" is already posted in a comment: https://stackoverflow.com/questions/32123394/workflow-to-create-a-folder-if-it-doesnt-exist-already/67060756#comment52139211_32123394 – Kajsa Gauza Apr 12 '21 at 16:11
  • 2
    @KasiaGauza But the comments aren't answers, and the op cannot accept a comment as an answer, sooooo what is wrong with his complete answer in this case? – Sinux1 Jun 29 '21 at 23:16
  • I think you're right, even if the author of the question accepted the answer in the comment – Kajsa Gauza Jun 30 '21 at 11:13
  • @Sinux1 the most correct way would probably to mark it as Community Wiki answer. See https://meta.stackoverflow.com/questions/343086/why-would-you-mark-an-answer-as-community-wiki for more details – j-i-l Jan 30 '22 at 19:50
5

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

scytale
  • 12,346
  • 3
  • 32
  • 46
1

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) 
ASAD HAMEED
  • 2,296
  • 1
  • 20
  • 36
  • Why have the `exist_ok` flag set to `True` if you're checking that it doesn't in fact exist already in the conditional? – Greenstick Apr 15 '22 at 22:35
  • Valid point. Can you make the edit if you have tested it? – ASAD HAMEED Apr 20 '22 at 09:52
  • I’ll be more direct — the conditional is redundant and adds no value. Both it and the `exists_ok` flag effectively make the `makedirs` operation idempotent, much like adding the `-p` flag to `mkdir` when doing the same operation on a Unix system. – Greenstick Apr 20 '22 at 22:07
1

This is a question of idempotence and 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 exist_ok flag to True (see the docs).

A Working Example

import os

directory = “my/test/directory/”

os.makedirs(directory, exist_ok = True)

Python 2

As mentioned in the original question, we can manually handle when a directory already exists by using a conditional and the os.path.exists method (see the docs) to check:

A Working Example

import os

directory = “my/test/directory/”

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

The above examples are both idempotent and, after multiple executions, you should get no error related to the directory already existing.

Greenstick
  • 8,632
  • 1
  • 24
  • 29
0
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()       
Karl
  • 1,664
  • 2
  • 12
  • 19