Python OS module, giving us the flexibility to access the directories, here we will see how to create or delete directories in python.

How to Create or Delete Directories in Python?

Getting the current working directory.

import os




The os.getcwd() gives us the directory path, which we are working currently. As you can see in the output, currently I an in D:\work\Python_repo directory.

Now let’s create some directories in Python_repo.

Python create directory:

To create a directory in python os.mkdir() method like below. It will create a directory on the current folder.

import os



prints the list of directories on the current working directory.



Python Create Sub Directories:

We can even create sub-directories within a directory using os.makedirs().

import os

It will create a sample-child directory under sample_dirs directory.

Python Delete Directory:

os.rmdir() function allows us to remove a specific directory.

import os 

The above program will not print anything, as have deleted sample_dir directory in the current working directory.

Python Delete Sub Directories:

As we have created subdirectories in the above, we can also remove the sub-directories using os.removedirs() function.

import os


The above program removes the specified directory path.

Happy Learning 🙂

About the Author:

Founder of Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment