How do I delete a directory tree with pathlib?
Question:
I have a project using pathlib
and I want to do the equivalent of shutil.rmtree
.
I thought of doing it with something like:
def pathlib_rmtree(folder):
if folder.exists():
for file in folder.glob('**/*'):
if file.is_dir():
file.rmdir()
else:
file.unlink()
folder.rmdir()
but I am not sure whether the folder.glob('**/*')
is guaranteed to be ordered so that all the subfolders are empty before calling rmdir
.
So the question is twofold:
- Is there a better way to recursively delete a directory with
pathlib
?
- Does
glob
guarantees the order of its result so that all the files are returned before the subfolder they belong to?
Answers:
Actually this can be done with iterdir
rather than glob
:
def rmtree(root):
for p in root.iterdir():
if p.is_dir():
rmtree(p)
else:
p.unlink()
root.rmdir()
I have a project using pathlib
and I want to do the equivalent of shutil.rmtree
.
I thought of doing it with something like:
def pathlib_rmtree(folder):
if folder.exists():
for file in folder.glob('**/*'):
if file.is_dir():
file.rmdir()
else:
file.unlink()
folder.rmdir()
but I am not sure whether the folder.glob('**/*')
is guaranteed to be ordered so that all the subfolders are empty before calling rmdir
.
So the question is twofold:
- Is there a better way to recursively delete a directory with
pathlib
? - Does
glob
guarantees the order of its result so that all the files are returned before the subfolder they belong to?
Actually this can be done with iterdir
rather than glob
:
def rmtree(root):
for p in root.iterdir():
if p.is_dir():
rmtree(p)
else:
p.unlink()
root.rmdir()