To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
use the shutil. rmtree() to recursively delete a directory and all files from it.
Deleting file/dir using the os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.
Try shutil.rmtree
:
import shutil
shutil.rmtree('/path/to/your/dir/')
The default behavior of os.walk()
is to walk from root to leaf. Set topdown=False
in os.walk()
to walk from leaf to root.
Here's my pure pathlib
recursive directory unlinker:
from pathlib import Path
def rmdir(directory):
directory = Path(directory)
for item in directory.iterdir():
if item.is_dir():
rmdir(item)
else:
item.unlink()
directory.rmdir()
rmdir(Path("dir/"))
Try rmtree()
in shutil
from the Python standard library
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With