Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to Create Directory If it Does Not Exist using Python?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, We will learn how to create a Directory if it Does Not Exist using Python.

Method 1: Using os.path.exists() and os.makedirs() methods

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
  
# checking if the directory demo_folder 
# exist or not.
if not os.path.exists("path/to/demo_folder"):
      
    # if the demo_folder directory is not present 
    # then create it.
    os.makedirs("path/to/demo_folder")

Output:

Method 2: Using isdir() and makedirs()

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
  
  
# checking if the directory demo_folder2 
# exist or not.
if not os.path.isdir("path/to/demo_folder2"):
    
    # if the demo_folder2 directory is 
    # not present then create it.
    os.makedirs("path/to/demo_folder2")

output:


My Personal Notes arrow_drop_up
Last Updated : 28 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials