PathLib recursively remove directory? PathLib recursively remove directory? python python

PathLib recursively remove directory?


As you already know, the only two Path methods for removing files/directories are .unlink() and .rmdir() and both doesn't do what you wanted.

Pathlib is a module to that provides object oriented paths across different OS's, it isn't meant to have lots of diverse methods.

The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them.

The "uncommon" file system alterations, such as recursively removing a directory, is stored in different modules. If you want to recursively remove a directory, you should use the shutil module. (It works with Path instances too!)

import shutilimport pathlibimport os  # for checking resultsprint(os.listdir())# ["a_directory", "foo.py", ...]path = pathlib.Path("a_directory")shutil.rmtree(path)print(os.listdir())# ["foo.py", ...]


Here's a pure pathlib implementation:

from pathlib import Pathdef rm_tree(pth):    pth = Path(pth)    for child in pth.glob('*'):        if child.is_file():            child.unlink()        else:            rm_tree(child)    pth.rmdir()


Otherwise, you can try this one if you want only pathlib:

from pathlib import Pathdef rm_tree(pth: Path):    for child in pth.iterdir():        if child.is_file():            child.unlink()        else:            rm_tree(child)    pth.rmdir()rm_tree(your_path)