How To Guide: Python create folder if not exists

Python Directory

Python is a simple yet widely-used programming language. Above all, it is intuitive and straightforward to make things manageable.

A directory or folders is a collection of files and subdirectories. And Python has a built-in OS module with useful methods in managing directories(or folders) and even files. 

OS Module

Python uses the OS module to interact with the operating system. It comes under Python’s standard utility modules and provides a portable way of using the operating system’s dependent functionality. 

To create a Python script for this problem, let’s use the os.path module. This Python submodule is used for common path name manipulation.

Use the following methods: 

  • os.path.isdir() - this function checks if a given directory existing or not.
  • os.makedirs() - this function checks creates a directory.

For example, to test how os.path.isdir() and os.makedirs() functions work. Let’s create a SampleFile.py file using these functions and run the program.

Program

<code>
#Python program to check if directory exists, if not, it will create a new 
#Importing os module
import os
#Declare the path directory
path = 'C:/Program Files/Common Files/AV/'
    
# Check whether the 
# specified path is an 
# existing directory or not 
isdir = os.path.isdir(path) 
print(isdir) 
#Declare a non-existing path directory
# Path 
path = 'C:/Program Files/Common Files/AV/xfiles.txt'
    
# Check whether the 
# specified path is an 
# existing directory or not 
isdir = os.path.isdir(path) 
print(isdir) 
# Create a folder if it doesn't exist
old_path = ("NewFiles")
new_path = os.path.isdir(old_path)
if not new_path:
    os.makedirs(old_path)
    print("Created Folder : ", old_path)
else:
    print(old_path, "folder already exists.")
</code>

Output:
True
False
Created Folder :  NewFiles

Explanation

Firstly, import the OS module. Secondly, declare the path directory using the path variable name. To show two scenarios, we use two existing and non-existing paths. Thirdly, use os.path.isdir(path) method to look for the folder on the system. 

As shown in the output, we have TRUE and FALSE results, respectively. True for the existing directory and FALSE for the non-existing directory.

In conclusion, to create a new directory, a set of conditional operation is executed using the os.makedirs(old_path) method.  

Note: Once you re-run the program it will display this output:
True
False
NewFiles folder already exists.

Because the new folder already exists; it executes the else statement in the program.

We will be happy to hear your thoughts

Leave a reply

Coders Eye - Web Dev Tutorials and How-To Guides for Beginners
Logo
Enable registration in settings - general