关于python:PathLib递归删除目录?

PathLib recursively remove directory?

有没有办法删除PathLib模块中的目录及其内容? 使用path.unlink()只删除文件,path.rmdir()目录必须为空。 在一个函数调用中没有办法吗?


如您所知,删除文件/目录的唯一两个Path方法是.unlink().rmdir(),两者都不能达到您想要的效果。

Pathlib是一个模块,它提供跨不同操作系统的面向对象的路径,它并不意味着有很多不同的方法。

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.

"不常见"的文件系统更改(例如递归删除目录)存储在不同的模块中。 如果要以递归方式删除目录,则应使用shutil模块。 (它也适用于Path实例!)

1
2
3
4
5
6
7
8
9
10
11
12
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", ...]


如果您不介意使用第三方库,请尝试使用path.py。
它的API类似于pathlib.Path,但提供了一些其他方法,包括Path.rmtree()以递归方式删除目录树。


否则,如果只需pathlib,可以尝试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
from pathlib import Path, os


def rm_tree(pth: Path):
    for f in os.listdir(pth):
        child = pth / f
        if child.is_file():
            child.unlink()
        else:
            rm_tree(child)
    pth.rmdir()

rm_tree(your_path)