Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: delete non-empty dir [duplicate]

Tags:

python

file

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

The directory may have nested subdirectories many levels deep.

like image 683
flybywire Avatar asked Oct 12 '09 22:10

flybywire


People also ask

What is the use of Rmtree () in Python?

rmtree() is used to delete an entire directory tree, path must point to a directory (but not a symbolic link to a directory). Parameters: path: A path-like object representing a file path.

How do I delete a non empty folder in Colab?

1 Answer. For removing/deleting any folder that is not empty with Python we have a standard library which is known as shutil. This library provides the function shutil. rmtree() which removes/deletes the non-empty folder.

How do I delete a non empty folder in Jupyter notebook?

“delete non empty directory python” Code Answer's os. rmdir('/your/folder/path/') #removes an empty directory. shutil. rmtree('/your/folder/path/') #deletes a directory and all its contents.


2 Answers

Use shutil.rmtree:

import shutil  shutil.rmtree(path) 

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

like image 158
RichieHindle Avatar answered Sep 28 '22 10:09

RichieHindle


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

like image 22
dgh Avatar answered Sep 28 '22 12:09

dgh