119

How do I delete a possibly non-empty dir in Python.

The directory may have nested subdirectories many levels deep.

0

3 Answers 3

189

Use shutil.rmtree:

import shutil

shutil.rmtree(path)

See the documentation for details of how to handle and/or ignore errors.

0
92

The standard library includes shutil.rmtree for this. By default,

shutil.rmtree(path)  # errors if dir not empty

will give OSError: [Errno 66] Directory not empty: <your/path>.

You can delete the directory and its contents anyway by ignoring the error:

shutil.rmtree(role_fs_path, ignore_errors=True)

You can perform more sophisticated error handling by also passing onerrror=<some function(function, path, excinfo)>.

5
  • 29
    ignore_errors=True means it does not remove the directory.
    – ostrokach
    Sep 3, 2015 at 17:50
  • 2
    ignore_errors=True was the tickket Sep 9, 2015 at 5:53
  • 8
    oh no, what a terrible name for parameter :( Mar 10, 2018 at 3:12
  • 2
    shutil.rmtree(path) will not give errors if the directory is empty in python 3.8, so this probably changed since you posted 6 years ago. Just wanted to update for other people viewing this now. Aug 30, 2020 at 18:31
  • shutil.rmtree(path) doesn't throw error if the directory not empty (python 3.7.9)
    – Max Segal
    Apr 10, 2022 at 8:33
12

You want shutil.rmtree

shutil.rmtree(path[, ignore_errors[, onerror]])

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

Not the answer you're looking for? Browse other questions tagged or ask your own question.