Python 3 - os.removedirs() Method


Description

The method removedirs() removes dirs recursively. If the leaf directory is succesfully removed, removedirs tries to successively remove every parent directory displayed in path. Raises OSError if the leaf directory could not be successfully removed.

Syntax

Following is the syntax for removedirs() method −

os.removedirs(path)

Parameters

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

Return Value

This method does not return any value.

Example

The following example shows the usage of removedirs() method.

# !/usr/bin/python3
import os, sys

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

# removing
os.removedirs("home\\monthly\\daily")

# listing directories after removing directory
print ("The dir after removal is:" %os.listdir(os.getcwd()))

Result

When we run the above program, it produces the following result −

The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer'
]
The dir after removal is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer'
]
python_files_io.htm
Advertisements