How to Create Directory If it Does Not Exist using Python?
Last Updated :
28 Nov, 2021
In this article, We will learn how to create a Directory if it Does Not Exist using Python.
Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if the directory doesn’t exist. makedirs() method is used to create demo_folder directory recursively .i.e. while creating demo_folder if any intermediate-level directory is missing then it will create all those intermediate missing directories. in the above case if the geeks_dir is not present then it will first create geeks_dir then it will create demo_folder
Directory Used:
Python3
import os
if not os.path.exists( "path/to/demo_folder" ):
os.makedirs( "path/to/demo_folder" )
|
Output:
In this method, we will use isdir() method takes path of demo_folder2 as an argument and returns true if the directory exists and return false if the directory doesn’t exist and makedirs() method is used to create demo_folder2 directory recursively .i.e. while creating demo_folder2 if any intermediate-level directory is missing then it will create all those intermediate missing directories. in the above case if the geeks_dir is not present then it will first create geeks_dir then it will create demo_folder2.
Directory Used:
Python3
import os
if not os.path.isdir( "path/to/demo_folder2" ):
os.makedirs( "path/to/demo_folder2" )
|
output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...