Working With Python Directory

This blog demonstrates how to work with a directory in Python including create a directory, rename a directory, and deleting a directory in Python.

Python Directory

 
In this blog, we will learn about directory management in Python.
 

Directory class

 
A directory is a collection of files and sub-directories. Python provides os modules for dealing with directories.
 
Some important directory method they are listed below:
  1. getcwd()
  2. chdir()
  3. listdir()
  4. path.exists()
  5. mkdir()
  6. rename()
  7. rmdir() 

Current Directory

 
getcwd() method is used to get your current working directory path. 
  1. import os  
  2. print(os.getcwd())  

Change Directory

 
Change your current working directory using chdir() method. It takes a full file path.
  1. import os  
  2. print(os.chdir('D:\\CCA'))  
  3. print(os.getcwd())  

List Directories and files

 
List all files and sub-directories inside a directory using listdir() method. The listdir() method take a full directory path. If you don't provide directory path then it takes the current working directory.
  1. import os  
  2. print(os.listdir())   
  3. print(os.listdir('D:\\CCA'))  

Check if a directory exists or not

 
The path.exists() method is used to check if a directory exists or not. If directory exists than returns TRUE else returns FALSE.
  1. import os  
  2. if os.path.exists('D:\\CCA\\Science'):  
  3. print('Directory already exists.')  
  4. else:  
  5. print('Directory doesn\'t exists.')  

Create a new directory

 
You can create a new directory using the mkdir() method. This method takes the full path of the new directory, if you don't provide a full path than the new directory is created in the current working directory.
  1. import os  
  2. os.chdir('D:\\CCA'#Change the current path  
  3. if os.path.exists('D:\\CCA\\Kumar'): #Check directory exists or not  
  4. print('Directory already exists.')  
  5. else:  
  6. os.mkdir('Kumar'#directory creating  
  7. print('Directory created successfully...')  

Rename a directory

 
You can rename a directory using rename() method. This method takes two arguments. The first argument is old directory name and the second argument is new directory name.
  1. import os  
  2. os.chdir('D:\\CCA')  
  3. if os.path.exists('D:\\CCA\\Kumar'):  
  4. os.rename('Kumar','Sarfaraj')  
  5. print('Directory is renamed successfully...')  
  6. else:  
  7. print('Drectory doesn\'t exists.')

Delete a directory

 
The rmdir() method is used to delete an empty directory. It takes a full file path.
  1. import os  
  2. os.chdir('D:\\CCA')  
  3. if os.path.exists('D:\\CCA\\Sarfaraj'):  
  4. os.rmdir('Sarfaraj')  
  5. print('Directory deteted successfully...')  
  6. else:  
  7. print('Drectory doesn\'t exists.')  

Summary

 
In this blog, I covered some directory related methods in python and saw examples of how to use these methods. Thanks for reading.