PathLib recursively remove directory?

PythonDirectoryPathlib

Python Problem Overview


Is there any way to remove a directory and it’s contents in the PathLib module? With path.unlink() it only removes a file, with path.rmdir() the directory has to be empty. Is there no way to do it in one function call?

Python Solutions


Solution 1 - Python

As you already know, the only two Path methods for removing files/directories are .unlink() and .rmdir() and neither does what you want.

Pathlib is a module 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 shutil
import pathlib
import os  # for checking results

print(os.listdir())
# ["a_directory", "foo.py", ...]

path = pathlib.Path("a_directory")

shutil.rmtree(path)
print(os.listdir())
# ["foo.py", ...]

Solution 2 - Python

Here's a pure pathlib implementation:

from pathlib import Path


def rm_tree(pth):
    pth = Path(pth)
    for child in pth.glob('*'):
        if child.is_file():
            child.unlink()
        else:
            rm_tree(child)
    pth.rmdir()

Solution 3 - Python

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

from pathlib import Path


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

Solution 4 - Python

If you don't mind using a third-party library give path a try. Its API is similar to pathlib.Path, but provides some additional methods, including Path.rmtree() to recursively delete a directory tree.

Solution 5 - Python

def rm_rf(basedir):
	if isinstance(basedir,str): basedir = pathlib.Path(basedir)
	if not basedir.is_dir(): return
	for p in reversed(list(basedir.rglob("*"))):
		if p.is_file(): p.unlink()
		elif p.is_dir(): p.rmdir()
	basedir.rmdir()

Solution 6 - Python

You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like rmtree

>>> python -m pip install pathlib3x

>>> import pathlib3x as pathlib

>>> my_path = pathlib.Path('c:/tmp/some_directory')
>>> my_path.rmtree(ignore_errors=True)


you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

Solution 7 - Python

Simple and effective:

def rmtree(f: Path):
    if f.is_file():
        f.unlink()
    else:
        for child in f.iterdir():
            rmtree(child)
        f.rmdir()

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
QuestionJasonca1View Question on Stackoverflow
Solution 1 - PythonTakuView Answer on Stackoverflow
Solution 2 - PythonMatteoLackiView Answer on Stackoverflow
Solution 3 - PythonRamiView Answer on Stackoverflow
Solution 4 - PythonAXOView Answer on Stackoverflow
Solution 5 - PythonzalavariView Answer on Stackoverflow
Solution 6 - PythonbitranoxView Answer on Stackoverflow
Solution 7 - Pythonmaf88View Answer on Stackoverflow