Create a directory in python using OS package

In this tutorial, I’m gonna show you how to create a directory in python using OS package.

How to create a directory in python

In python, there is a slightly easy method to create a directory by the help of python coding .so in this program we are going to import os module first.

#import os package to  use all the in-built function like mkdir.
import os

Now create a main function which takes directory name and using some function it will create a new directory

#define directory function which handles all the directory operation.
def Directory():

Take directory name from users and create within the folder.

# Create directory , it's a directory name which you are going to create.
   
   Directory_Name = input("Enter the directory name ")

now we are going to take try and catch block to handle the exception during the program execution and we placed all the main code within that block.

#try and catch block use to handle the exceptions.
    try:
        # Create  Directory  MyDirectory 
        os.mkdir(Directory_Name)
        #print if directory created successfully...
        print("Directory " , Directory_Name ,  " Created") 
    except FileExistsError:
        ##print if directory already exists...
        print("Directory " , Directory_Name ,  " already exists...")

now combine the whole part of the program:

#import os package to  use all the in-built function like mkdir.
import os
#define directory function which handles all the directory operation.
def Directory():
    
    # Create directory ,it's a directory name which you are going to create.
    
    Directory_Name = input("Enter the directory name ")
    #try and catch block use to handle the exceptions.
    try:
        # Create  Directory  MyDirectory 
        os.mkdir(Directory_Name)
        #print if directory created successfully...
        print("Directory " , Directory_Name ,  " Created ") 
    except FileExistsError:
        ##print if directory already exists...
        print("Directory " , Directory_Name ,  " already exists...")        
    
#Directory function call...    
Directory()

Output1:

Directory Directory_Name Created

Output2:

Directory Directory_Name already exists...

Some other tutorials,

Leave a Reply

Your email address will not be published. Required fields are marked *