In this article, we have explained the process to create a directory in Python using the os module.
Table of contents:
- Create Directory in Python
- Complete Code
Create Directory in Python
A directory can be created using os module. So, import os module in Python:
To create a directory, mkdir() function of os module can be used. It will work only when the directory does not exist already and all nested directories are already created (only final directory needs to be created).
To avoid the case where the directory already exists, we can use the path.exists() function of os module to check if the directory exists and can be created accordingly. The code snippet will be as follows:
if ! os.path.exists("directory1"): os.mkdir("directory1")
Following is the complete Python code to create directory:
import os # Create a directory in PWD named as directory1 if ! os.path.exists("directory1"): os.mkdir("directory1") print ("Directory created") else: print ("Directory exists")
With this article at OpenGenus, you must have the complete idea of how to create a directory in Python.