Added delete_empty_folders() and delete_folder()

This commit is contained in:
2Shirt 2019-09-15 16:50:06 -07:00
parent 7a99713043
commit 010ac87de6
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C

View file

@ -1,10 +1,36 @@
'''WizardKit: I/O Functions'''
# vim: sts=2 sw=2 ts=2
import os
import shutil
import pathlib
# Functions
def delete_empty_folders(path):
"""Recursively delete all empty folders in path."""
# Delete empty subfolders first
for item in os.scandir(path):
if item.is_dir():
delete_empty_folders(item.path)
# Attempt to remove (top) path
try:
delete_folder(path, force=False)
except OSError:
# Assuming it's not empty
pass
def delete_folder(path, force=False):
"""Delete folder if empty or if forced."""
if force:
shutil.rmtree(path)
else:
os.rmdir(path)
def non_clobbering_path(path):
"""Update path as needed to non-existing path, returns pathlib.Path."""
path = pathlib.Path(path)