PathLib recursively remove directory?
有没有办法删除PathLib模块中的目录及其内容? 使用
如您所知,删除文件/目录的唯一两个
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.
"不常见"的文件系统更改(例如递归删除目录)存储在不同的模块中。 如果要以递归方式删除目录,则应使用
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类似于
否则,如果只需
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) |