Directory handling in python

You can perform various directory related operation using os module in python. Let’s see some of the operation we can perform in directory.

Getting current directory

Knowing which workspace we are working on, is sometimes important. We can use getcwd() method on the os module to know the current working directory. 


import os
current_path = os.getcwd()


you will get the current working directory path

Creating a directory

You can use mkdir(pathtofile) method to create a directory. If the directory already exists it will throw error. Therefore we need to check if the directory exists or not and then create it. Let’s see an example

import os
# create python_is_awesome directory


It creates a directory name ‘python_is_awesome’.

You can check if the directory with this name is present or not with os.path.isdir(directory_path). Let’s see the an example

import os
directory_name = 'python_is_awesome'
if not os.path.isdir(directory_name):

You only create a directory if the directory is not present. Otherwise you skip creation. 

Renaming a directory

You can rename a directory with os.rename(old_dir_path, new_dir_path). Let’s see an example

import os
os.rename('python_is_awesome', 'python_is_everywhere')

If the directory is not present it will throw an error therefore like before we need to check if the directory with that name is available or not.

Removing a directory

You can use os.rmdir(dir_path) to remove a directory. Let’s see an example

import os

Listing file or directory in current working directory

You can use os.listdir(path=’.’) method to list directories or file. If no path is given it will return list of file and directories of current working directory.


import os

This is same as

import os

The dot (‘.’) represents current working directory. Output: Gives list of directory in the current location.

Leave a Reply

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