How to create new folder/directory in Python / Safely create a nested directory?
There are some situation during our programming life that we need to create folder for different purbpses. Like, if I want to put output information of my program to a folder then I need to ceate a folder or check folder is there or not. If the folder does not exist, then the program should create a new folder with folder name as given in the program. But if it is already there then what to do? We dont need to create the folder. We cad proceed the programming.
import os
def createFolder(folderName):
try:
if not os.path.exists(folderName):
os.makedirs(folderName)
print('folder created successfully!')
else:
print('folder alreay existed!')
except OSError:
print('Error - Folder Createion')
createFolder('a1')
createFolder('a2')
That is the code for createing an empty folder. And its a safe programming practices also. If you need to create nested directory, you can just implement the loop and then just call this python functon. So, it will do its job