# How to remove a directory using Python?

ProgrammingPythonServer Side Programming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

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
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
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
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 06:53:57