skip to content
Jakub Szafran

Removing non-empty directory in Python

/ 1 min read

I recently needed to remove whole directory from a Python script (non-empty one).

I usually use pathlib module for managing operation on files. However, .rmdir() method works only on empty directories.

While you could always try to walk recursively through the tree and use unlink()/rmdir() methods, I found out that this can be handled with a simple one-liner from shutil module:

import pathlib
import shutil


non_empty_dir = pathlib.Path("some_non_empty_directory")
shutil.rmtree(non_empty_dir)

If you’d like to make above statement idempotent (so for example it would not fail if some_non_empty_directory does not exists), then set ignore_errors to True:

import pathlib
import shutil


non_empty_dir = pathlib.Path("some_non_empty_directory")
shutil.rmtree(non_empty_dir, ignore_errors=True)

Hope you find it useful,

Kuba