Add my script for removing empty directories
- ID
70dedac- date
2022-03-19 09:15:36+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
28fb060- message
Add my script for removing empty directories- changed files
1 file, 33 additions
Changed files
emptydir (0) → emptydir (724)
diff --git a/emptydir b/emptydir
new file mode 100755
index 0000000..a998174
--- /dev/null
+++ b/emptydir
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+"""
+This script walks a directory tree, looks for empty directories,
+and removes them.
+
+It prints the name of every directory it removes.
+"""
+
+import os
+import shutil
+
+
+def can_be_deleted(d):
+ entries = os.listdir(d)
+ return entries == [".DS_Store"] or not entries
+
+
+def delete_directory(d):
+ assert can_be_deleted(d)
+ print(d)
+ shutil.rmtree(d)
+
+ # Was this the only entry in its parent directory? Unwind one level
+ # to see if we can delete the parent also.
+ parent = os.path.dirname(d)
+ if can_be_deleted(parent):
+ delete_directory(parent)
+
+
+if __name__ == "__main__":
+ for d, _, _ in os.walk("."):
+ if can_be_deleted(d):
+ delete_directory(d)