Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 327
RafaelGP Avatar asked Aug 20 '15 16:08

RafaelGP


2 Answers

you can use the below

# file handler
import os
filename = "./logs/mylog.log"
os.makedirs(os.path.dirname(filename), exist_ok=True)
like image 154
Rajesh Selvaraj Avatar answered Oct 21 '22 12:10

Rajesh Selvaraj


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) 
like image 45
ASAD HAMEED Avatar answered Oct 21 '22 12:10

ASAD HAMEED