python

How to Recursively Remove a Directory in Python

In this tutorial, we are going to see how to remove an empty directory as well as its content recursively, including the content of its subdirectories.
 

Remove an empty directory

Python’s os module provides the function os.rmdir(path) allowing to delete an empty directory. The directory path can be relative or absolute. Example:

import os

#Remove a directory
try:
    os.rmdir('/home/rep')
except:
    print('Error deleting directory')
 

Remove a directory recursively

In Python the “shutil” module provides the function shutil.rmtree(path) to remove all the contents of a directory. Example:

import shutil

path = '/home/dir/';
# Remove all directory content
try:
    shutil.rmtree(path)
except:
    print('Error deleting directory')

It removes all the contents of “dir” directory.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *