python: delete non-empty dir

PythonFile

Python Problem Overview


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

The directory may have nested subdirectories many levels deep.

Python Solutions


Solution 1 - Python

Use shutil.rmtree:

import shutil

shutil.rmtree(path)

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

Solution 2 - Python

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)>.

Solution 3 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflybywireView Question on Stackoverflow
Solution 1 - PythonRichieHindleView Answer on Stackoverflow
Solution 2 - PythondghView Answer on Stackoverflow
Solution 3 - PythonAndrew DalkeView Answer on Stackoverflow