@@ -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+
461484def calculate_directory_size_bytes (path : str ) -> int :
462485 """
463486 Calculate recursive directory size in bytes.
0 commit comments