Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting folders in python recursively

People also ask

How do I delete a recursive folder?

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.

How do I delete a recursive file in Python?

use the shutil. rmtree() to recursively delete a directory and all files from it.

Can you delete a folder with Python?

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