Python delete directory

With Python, you can automate operations on files and directories. This notebook shows how to use the Python built-in module shutil. It has rmtree() function that can be used to remove directories.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

The shutil.rmtree() can remove empty directory and directory with files. We run it in try ... except block because it may raise Exception if directory doesn't exist or for other reasons (missing rights to delete).

We will use documents directory in this notebook:

documents/
├── music
│   ├── bass-guitar-sample.mp3
│   ├── first-song.mp3
│   ├── italo-disco.mp3
│   └── rave.wav
├── my-cv.pdf
├── phd-thesis.txt
├── todo.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov

Let's remove documents/music directory.

# import packages
import shutil
# try to delete directory
try:
    shutil.rmtree(r"/home/piotr/documents/music")
except Exception as e:
    print(f"Error during directory delete, {str(e)}")

Let's check documents directory after running above code:

documents/
├── my-cv.pdf
├── phd-thesis.txt
├── todo.txt
└── video
    ├── holidays-2023.mp4
    ├── holidays-2024.mp4
    └── zoo.mov

1 directory, 6 files

You can see that the the music directory and all files in it are deleted. Please be careful when using shutil.rmtree() because you can quickly remove all your directories. Take care!

Recipes used in the python-delete-directory.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-delete-directory.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.