The task is to delete empty folders. The code below only deletes the last folder and turns off. But, after deleting the last folder, the folder in which it was located also becomes empty. How to make the script after deleting the last folder check the folder from which it deleted the last one and deleted it?

def del_empty_dirs(path): for d in os.listdir(path): a = os.path.join(path, d) if os.path.isdir(a): if not os.listdir(a): os.rmdir(a) print(a, 'удалена') else: del_empty_dirs(a) 

    1 answer 1

    You need a depth search ..
    First, we delve into recursion, only then we check / delete something:

     def del_empty_dirs(path): for d in os.listdir(path): a = os.path.join(path, d) if os.path.isdir(a): del_empty_dirs(a) if not os.listdir(a): os.rmdir(a) print(a, 'удалена') 

    Thus, we guarantee that after leaving the recursive call - all child folders have already been processed.

    • Thank you very much! - Igor