Python program to check and create one directory
Python OS module provides different methods to perform different operating system tasks like create a directory, delete a directory, etc. In this post, we will learn how to check if a directory exists or not and to create one directory if it doesn’t exist.
Methods to use :
We will use the python os module and the following methods of this module :
1. os.path.isdir(path) :
This method takes one argument, the path of the directory. It returns True if path is an existing directory. Else, it returns False.
2. os.mkdir :
This method is used to create one directory. We can pass the path of a directory to this method and it will create one as defined by the path. It throws one FileExistsError if the folder already exists.
Python program :
Below python program will check if a folder exists or not in the current directory and create it if it doesn’t exist.
import os DIR_NAME = "Example-dir" if os.path.isdir(DIR_NAME): print(DIR_NAME, "already exists.") else: os.mkdir(DIR_NAME) print(DIR_NAME, "is created.")
This program will create one directory in the same folder.
We can wrap the mkdir line in a try-catch block if we don’t use the if condition.
Similar tutorials :
- Python program to check if a number is abundant/excessive or not
- Use any() function in python to check if anything inside a iterable is True
- Four different methods to check if all items are similar in python list
- Python tutorial to check if a user is eligible for voting or not
- Python program to check if two strings are an anagram or not
- Python program to check if an array is monotonic or not