How to remove a directory using Python?


Directories and files can be deleted using Python's built-in modules and functions. Removing files or directories is a significant process since, after you've destroyed a directory, it's difficult to get its contents back. Therefore, users can remove the directory and its contents without much difficulty by applying a few useful Python functions.

Python has the following functions for removing a directory or folder −

Using os.rmdir() function

Python uses the os.rmdir() function to delete empty directories. In this scenario, the required directory must be empty; else, an OSError would be raised. If the directory doesn't exist, the FileNOtFoundError is thrown.

Example

Following is an example to remove a directory using os.rmdir() function −

import os path = 'C:\Users\Lenovo\Downloads\New folder' try: os.rmdir(path) print("directory is deleted") except OSError as x: print("Error occured: %s : %s" % (path, x.strerror))

Output

Following is an output of the above code −

directory is deleted

The 'path' variable will save the path to the directory you want to remove.

Using pathlib module

The Path.rmdir() function also helps in deleting an empty directory by including the pathlib module.

Example

Following is an example to remove a directory using path.rmdir() function −

from pathlib import Path path= Path('C:\Users\Lenovo\Downloads\New folder') try: path.rmdir() print("Directory is removed successfully") except OSError as x: print("Error occured: %s : %s" % (path, x.strerror))

Output

Following is an output of the above code −

Directory is removed successfully

The path to the directory you want to remove is stored in the path variable.

Using shutil.rmtree() function

You can delete or remove the required directory and its contents from your system using the shutil.rmtree() function. Therefore, to remove a directory tree, use the shutil module.

Example

Following is an example to remove a directory using shutil.rmtree() function: −

import shutil path = 'C:\Users\Lenovo\Downloads\Work TP' try: shutil.rmtree(path) print("directory is removed successfully") except OSError as x: print("Error occured: %s : %s" % (path, x.strerror))

Output

Following is an output of the above code −

directory is removed successfully

Updated on: 18-Aug-2022

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements