Explore

Close
HowTos Share

How To Create a Folder In Python If Not Exists

How To Create A Folder In Python If Not Exists

You searched for Python create folder if not exists. If you want to know how to create a folder in python if it does not exists then in this tutorial I will show you how to create a folder in python if not exists.

This is going to be very simple and easy to do. I will show you two methods to create a folder in python if it does not exists I will show you step by step with code so follow up with me till the end.

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

The Complete Python Programming Boo...
The Complete Python Programming Bootcamp

#1 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')

As you can see from the above code, first you need to import the os module which is responsible for folder checking and creation.

Then we have used if else inside if we check if not os.path.exists(‘folder_name’) this means check if there is a folder named with this you need to enter the folder name you want to check.

If the folder exists it will not create anything, but if it does not exists it will create a folder with folder_name.

#2 Creating a folder in python if not exists using try and except


import os
try:
    os.makedirs('my_folders')
except OSError as e:
    print(e)

This is another way of creating a folder in python if it does not exists by using the try and except try will run and it will try to create a folder and if the folder exists it will throw an error which will be handled in the except.

This way looks simple and clean, you can use the if else statements or use this it’s your choice both ways work perfectly.

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 python problem. If you want more updates from us, then join our Telegram channel for daily python guides.

Thank you for watching, have a nice day 🙂