In this tutorial, we would learn about the Directory in Python. In Directories, we can store files and subdirectories. Directories help us to manage a large amount of files of our project. There is an os module in Python which provides us with methods to work with Directories.

Get Current Directory:

Here will we will learn how we can get the current working directory. There is .getcwd() method in the os module which helps us to get the current working directory. Follow this example to understand these methods.

import os

print(os.getcwd())

Changing Directory:

We can change our current working directory using chdir() method. We have to mention the new path in this method. we can separate path elements using backslash or forward slash.

import os

print(os.getcwd())

os.chdir('C:\\Python')

print(os.getcwd())

Check complete list of Directories and files:

In Python os module provide us method called listdir(). which return list of all the available subdirectories and files in the current directory.

import os

print(os.getcwd())

os.listdir()

Create a Directory:

In Python os module provide us method called mkdir() which helps us to create new directory. In this method, we provide full path where we want to create a directory in case we don’t provide full path it will create Directory in the current directory.

import os

os.mkdir('test')

os.listdir();

Renaming a Directory:

We can rename a directory using rename() method. This rename method takes two arguments first one is the old name of the directory and the second one in the new name of the directory. Check this example below

import os

os.rename('test','My_Directory')

os.listdir();

Removing a Directory:

We can remove the existing file using method call remove() and can remove a directory using rmdir() method. These methods take only one parameter which is the directory/filename which you want to delete. Check this example.

import os

os.rmdir('My_Directory')

os.listdir();

Download Jupyter NoteBook File: