Python os.removedirs() Method



The Python os.removedirs() method removes directories recursively. It is used when we want to delete an entire directory tree.

The os.removedirs() works similarly to the os.rmdir(). However, the only difference is that if os.removedirs() method removes the leaf directory successfully, it tries to successively remove every parent directory displayed in path. The process continues until it encounters a non-empty directory.

Syntax

Syntax of Python os.removedirs() method is as follows −

os.removedirs(path)

Parameters

The Python os.removedirs() method accepts a single parameter −

  • path − This is the path of the directory, which needs to be removed.

Return Value

The Python os.removedirs() method does not return any value.

Example

The below example shows the basic use of removedirs() method. Here, we are trying to remove "tutorialsdir" directory.

import os, sys

# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))

# removing
os.removedirs("/home/tp/Python/tutorialsdir")

# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))

When we run above program, it produces following result −

The dir is:
[  'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal is:
[  'a1.txt','resume.doc','a3.py','amrood.admin' ]

Example

The removedirs() method raises a "NotADirectoryError", if the specified path is not a directory and raises OSError, if the given directory is not empty or does not exist.

import os

# Path to the directory you want to remove
path = "/home/tp/Python/newdir"

try:
   # removing the directory
   os.removedirs(path)
except OSError as exp:
   print(f"Error: {exp.strerror}")

When we run above program, it produces following result −

Error: No such file or directory
python_files_io.htm
Advertisements