Skip to content

Instantly share code, notes, and snippets.

@ryanlong1004
Forked from jacobtomlinson/remove_empty_folders.py
Last active January 18, 2022 02:31
Show Gist options
  • Save ryanlong1004/c69d3f0e4c6210ef7387338c892afc38 to your computer and use it in GitHub Desktop.
Save ryanlong1004/c69d3f0e4c6210ef7387338c892afc38 to your computer and use it in GitHub Desktop.
Python Recursively Remove Empty Directories
#! /usr/bin/env python
"""
Module to remove empty folders recursively. Can be used as standalone script or be imported into existing script.
"""
import os
import argparse
import pathlib
import asyncio
import logging
from functools import lru_cache
def get_args():
"""get_args display CLI to user and gets options
Returns:
Namespace: object-
"""
parser = argparse.ArgumentParser(
description="Recursively removes empty directories."
)
parser.add_argument(
"root_path",
type=pathlib.Path,
help="path to begin search from",
)
parser.add_argument(
"-n",
"--name",
help=("remove root"),
)
return parser.parse_args()
@lru_cache
async def remove_empty_folders(_path, remove_root=True):
"""remove_empty_folders removes empty folders recursively
Args:
_path (Path): root path
remove_root (bool, optional): True to remove the root path. Defaults to True.
"""
if not os.path.isdir(_path):
return
# remove empty subfolders
files = os.listdir(_path)
if len(files):
search = set(
os.path.join(_path, _file)
for _file in files
if os.path.isdir(os.path.join(_path, _file))
)
await asyncio.gather(
*(remove_empty_folders(item) for item in search), return_exceptions=True
)
# if folder empty, delete it
files = os.listdir(_path)
if len(files) == 0 and remove_root:
print("Removing empty folder: {_path}")
logging.info("Removing empty folder: %s", _path)
# os.rmdir(_path)
async def main(root_path):
"""Main execution"""
await remove_empty_folders(root_path, False)
if __name__ == "__main__":
import timeit
args = get_args()
starttime = timeit.default_timer()
loop = asyncio.get_event_loop()
loop.run_until_complete(main(args.root_path))
logging.debug("The time difference is :%s", timeit.default_timer() - starttime)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment