Skip to content

Commit 11fa345

Browse files
FEAT: Removing empty directories after cleanup in ./main_subdirs.py
1 parent 80900bd commit 11fa345

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

Folder Size Tagger/main_subdirs.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,7 @@ def delete_image_files_in_directory(path: str) -> None:
443443

444444
if os.path.isdir(file_path): # Verify current entry is a directory
445445
delete_image_files_in_directory(file_path) # Recursively process subdirectory
446+
remove_empty_directory(file_path) # Remove the subdirectory if deletions left it empty
446447
continue # Continue to next entry after recursion
447448

448449
if not os.path.isfile(file_path): # Verify current entry is a file.
@@ -458,6 +459,28 @@ def delete_image_files_in_directory(path: str) -> None:
458459
continue # Skip files that cannot be removed.
459460

460461

462+
def remove_empty_directory(path: str) -> bool:
463+
"""
464+
Remove a directory only when it has no remaining entries.
465+
466+
:param path: Directory path to remove when empty.
467+
:return: True when the directory was removed, False otherwise.
468+
"""
469+
470+
try: # Protect directory validation and listing
471+
if not os.path.isdir(path): # Verify if the path is not an existing directory
472+
return False # Nothing was removed
473+
474+
if os.listdir(path): # Verify if the directory still contains entries
475+
return False # Keep non-empty directories untouched
476+
477+
os.rmdir(path) # Remove the empty directory
478+
DELETION_STATS["dirs_deleted"] += 1 # Increment deleted directories counter for empty dir
479+
return True # Report successful removal
480+
except (PermissionError, OSError): # Handle deletion access failures
481+
return False # Report that the directory was not removed
482+
483+
461484
def calculate_directory_size_bytes(path: str) -> int:
462485
"""
463486
Calculate recursive directory size in bytes.

0 commit comments

Comments
 (0)