From 010ac87de633d37b278aba0d87ca493fc4d5b94e Mon Sep 17 00:00:00 2001 From: 2Shirt <2xShirt@gmail.com> Date: Sun, 15 Sep 2019 16:50:06 -0700 Subject: [PATCH] Added delete_empty_folders() and delete_folder() --- scripts/wk/io.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/scripts/wk/io.py b/scripts/wk/io.py index d991be4a..d9637716 100644 --- a/scripts/wk/io.py +++ b/scripts/wk/io.py @@ -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)