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.
you can use the below
# file handler
import os
filename = "./logs/mylog.log"
os.makedirs(os.path.dirname(filename), exist_ok=True)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With