Monday, September 23, 2024
Google search engine
HomeLanguagesHow to Create Directory If it Does Not Exist using Python?

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

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 Lazyroar_dir is not present then it will first create Lazyroar_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 Lazyroar_dir is not present then it will first create Lazyroar_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:

RELATED ARTICLES

Most Popular

Recent Comments