Last active
November 12, 2022 14:12
-
-
Save daephx/a369caba8b1fd4963b2ae08b985db496 to your computer and use it in GitHub Desktop.
[Remove Empty Folder] Recursively delete empty directories #Python #Scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This script will recursively delete empty directories. | |
Script will default to the current directory, | |
Handled input with care, | |
A successful operation CANNOT be undone! | |
""" | |
import argparse | |
import os | |
import sys | |
parser = argparse.ArgumentParser(description="remove empty directories.", add_help=False) | |
parser.add_argument( | |
"-h", "--help", action="help", default=argparse.SUPPRESS, help="display help information for the current script." | |
) | |
parser.add_argument( | |
"-d", | |
"--dirs", | |
default=os.getcwd(), | |
metavar="PATH", | |
type=str, | |
nargs="*", | |
help="specify the directory for the script to search.", | |
) | |
args = parser.parse_args() | |
def delete_empty_folders(dir): | |
""" Recursively check folder contents and attempts to delete any empty folders. """ | |
for root, dirs, files in os.walk(dir, topdown=False): | |
for name in dirs: | |
try: | |
# Check whether the directory is empty | |
if len(os.listdir(os.path.join(root, name))) == 0: | |
print("Deleting:", os.path.join(root, name)) | |
try: | |
os.rmdir(os.path.join(root, name)) | |
except Exception: | |
print("Failure:", os.path.join(root, name)) | |
continue | |
except Exception: | |
pass | |
def query_yes_no(question, default="no"): | |
""" Verification of working directory prior to execution of folder deletion method. """ | |
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} | |
if default is None: | |
prompt = "[y/n] " | |
elif default == "yes": | |
prompt = "[Y/n] " | |
elif default == "no": | |
prompt = "[y/N] " | |
else: | |
raise ValueError("Invalid default answer: '%s'" % default) | |
while True: | |
sys.stdout.write(question + prompt) | |
choice = input().lower() | |
if default is not None and choice == "": | |
return valid[default] | |
elif choice in valid: | |
return valid[choice] | |
else: | |
sys.stdout.write("Please type 'yes' or 'no' " "(or 'y' or 'n').\n") | |
if __name__ == "__main__": | |
try: | |
dirs = [] | |
dirs.append(args.dirs) | |
print(f"\nThis will delete ALL empty folders in: \n{dirs}\n") | |
if query_yes_no("Are you sure you want to continue?: "): | |
for x in dirs: | |
delete_empty_folders(x) | |
print("\nProcess Completed!") | |
else: | |
print("\nProcess Terminated!") | |
except KeyboardInterrupt: | |
pass | |
else: | |
print(f"Cannot run {__name__}.py as module.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment