Remove empty folders (Python)

This is the folder tree:

FOLDER\\
       \\1\\file
       \\2\\file
       \\3\\
       \\4\\file

The script should scan (loop) for each folder in FOLDER and check if the sub-folders are empty or not. If they are, they must be deleted.

My code, until now, is this:

folders = ([x[0] for x in os.walk(os.path.expanduser('~\\Desktop\\FOLDER\\DIGITS\\'))])
folders2= (folders[1:])

This scan for folders and, using folders2 begin from the firs folder in DIGITS. In DIGITS there are numbered directories: 1,2,3,4,etc

Now what? Tried using os.rmdir but it gives me an error, something about string. In fact, folders2 is a list, not a string, just saying...


Solution 1:

Not sure what kind of error you get, this works perfectly for me:

import os

root = 'FOLDER'
folders = list(os.walk(root))[1:]

for folder in folders:
    # folder example: ('FOLDER/3', [], ['file'])
    if not folder[2]:
        os.rmdir(folder[0])

Solution 2:

You can remove all empty folders and subfolder with the following snippet.

import os


def remove_empty_folders(path_abs):
    walk = list(os.walk(path_abs))
    for path, _, _ in walk[::-1]:
        if len(os.listdir(path)) == 0:
            os.remove(path)

if __name__ == '__main__':
    remove_empty_folders("your-path")

Solution 3:

Delete folder only if it is empty:

import os
import shutil

if len(os.listdir(folder_path)) == 0: # Check if the folder is empty
    shutil.rmtree(folder_path) # If so, delete it

Solution 4:

import os

directory = r'path-to-directory'

for entry in os.scandir(directory):
    if os.path.isdir(entry.path) and not os.listdir(entry.path) :
        os.rmdir(entry.path)

Here you can find a good introduction/explanation to scandir