Directory and Files Management in Python

In this post, you’ll learn about file and directory management in Python, i.e. creating a directory, renaming it, listing all directories and working with them.

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.

import os  
print(os.getcwd())  

Change Directory

Change your current working directory using chdir() method. It takes a full file path.

import os  
print(os.chdir('D:\\CCA'))  
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.

import os  
print(os.listdir())   
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.

import os  
if os.path.exists('D:\\CCA\\Science'):  
print('Directory already exists.')  
else:  
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.

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 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.

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.')

Delete a directory

The rmdir() method is used to delete an empty directory. It takes a 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.')  

Summary

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

#python #Directory # Files Management

Directory and Files Management in Python
18.40 GEEK