Home
| Colors: |
February 2026

Empty a Folder in Python

This is how I clear out everything inside a directory while leaving the directory itself intact using Python:

import shutil
from pathlib import Path 

def empty_folder(path):
    for item in Path(path).iterdir():
        shutil.rmtree(item) if item.is_dir() else item.unlink()

No fuss. No muss. Pythonic style.

-a

end of line

Endnotes

Something else to look at is send2trash which sends stuff to the trash/recycle bin instead of straight up deleting them.

Most of the time I want to remove stuff completely with scripts but there are times when it would be nice to have a fallback in case something gets killed that shouldn't be.