Directory management in Python

In this blog, we will see how we can manage directory-related work in Python, so let’s get started.

Directory class

Basically, a directory is a collection of files and sub-directories. Python provides os modules that manage directory-related operations. Here are a few important directories method:

  • getcwd()
  • chdir()
  • listdir()
  • path.exists()
  • mkdir()
  • rename()
  • rmdir()

getcwd

The getcwd() method returns the path to your current working directory.

import os  
print(os.getcwd())  

chdir

The chdir() method changes the current working directory. To change the directory, it requires a full path.

import os  
print(os.chdir('D:\\CCA'))  
print(os.getcwd())  

listdir

You can use listdir() to list all files and directories in a directory. This method takes a full directory path.

Note: If you don’t specify a directory path, it will take the current working directory.

import os  
print(os.listdir())   
print(os.listdir('D:\\CCA'))

path.exists

The path.exists() method is used to determine whether a directory exists. It returns TRUE if the directory exists, otherwise it returns FALSE.

import os  
if os.path.exists('D:\\CCA\\Science'):  
print('Directory already exists.')  
else:  
print('Directory doesn\'t exists.') 

mkdir

The mkdir() method allows you to create a new directory. A full path for the new directory is required, otherwise the new directory is created in the current working directory.

import os  
os.chdir('D:\\CCA') #Change the current path  
if os.path.exists('D:\\CCA\\Kumar'): #Check directory exists or not  
print('Directory already exists.')  
else:  
os.mkdir('Kumar') #directory creating  
print('Directory created successfully...')

rename

Using the rename() method, you can rename a directory. It takes two arguments. The first argument is the old directory name, and the second argument is the new directory name.

import os  
os.chdir('D:\\CCA')  
if os.path.exists('D:\\CCA\\Kumar'):  
os.rename('Kumar','Sarfaraj')  
print('Directory is renamed successfully...')  
else:  
print('Drectory doesn\'t exists.')

rmdir

To remove an empty directory, use the rmdir() method. It takes the full file path.

import os  
os.chdir('D:\\CCA')  
if os.path.exists('D:\\CCA\\Sarfaraj'):  
os.rmdir('Sarfaraj')  
print('Directory deteted successfully...')  
else:  
print('Drectory doesn\'t exists.')  

Conclusion

In this blog, I covered some directory-related methods in Python and provided examples of how to use these methods. Thank you for reading.

Leave a Reply

Your email address will not be published.