Pythondex
Python Programs

How To Create a Folder In Python If Not Exists

Last updated April 21, 2023 by Jarvis Silva

In this tutorial you will learn how to create a folder in python if not exists meaning if a folder is not present in the directory with that name you create it using python.

To create a folder in python we will use the builtin os module which comes preinstalled with python so you don’t need to install anything.

I will assume that you have python setup and installed on your computer. If you don’t have it, then you can follow this guide: Install and setup python.

Creating a folder in python if not exists using if else


import os

if not os.path.exists('my_folder'):
    os.makedirs('my_folder')
else:
    print('folder already exists')

In the above code we use the os.path.exists(‘folder_name’) to check if the folder exists with that name then if not exists then it creates the folder with os.makedirs(‘folder_name’) else if exists it will print folder already exists and exit the program.

Here are more python guides you can read:

I hope you found what you were looking for and this guide helped you to solve your problem. If you want more tutorials like this then join our Telegram channel to stay updated.

Thank you for reading, have a nice day 🙂