Skip to content

Instantly share code, notes, and snippets.

@Mehanik
Created February 28, 2023 15:52
Show Gist options
  • Save Mehanik/24f70288d162518f585bbea64b23d9e2 to your computer and use it in GitHub Desktop.
Save Mehanik/24f70288d162518f585bbea64b23d9e2 to your computer and use it in GitHub Desktop.
Remove directories with size less then threshold (for example, empty tensorboard directories)
#!/usr/bin/env python3
import argparse
import os
import shutil
def dir_size(p):
return sum(os.path.getsize(f) for f in os.scandir(p) if f.is_file())
def main():
parser = argparse.ArgumentParser(
prog="remove_empty",
description="Remove small size directories",
)
parser.add_argument("path", nargs="?", default=os.getcwd())
parser.add_argument("--th", type=int, default=3771, help="file size threshold")
parser.add_argument("-y", "--yes", action="store_true", help="do not ask")
args = parser.parse_args()
dirs = [(d, dir_size(d)) for d in os.scandir(args.path) if d.is_dir()]
to_remove = [d for d, s in dirs if s <= args.th]
if len(to_remove) == 0:
print("Nothing to do")
return
print("This directories will be removed:")
print()
print("\n".join([d.__fspath__() for d in to_remove]))
print()
if not args.yes:
confirmation = input("Remove this files (yes/no): ")
if confirmation.lower() == "yes":
pass
else:
return
for d in to_remove:
shutil.rmtree(d)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment