Remove subfolders with the same name if empty

Advertisements

Assuming I have a folder called trial that contains the following:
Folder1, Folder2, Folder3,…Folder5
And each of these folders has a subfolder called FF-15

Thus, the path is:
'/Users/brianadams/school/trial/Folder1/FF-15', or '/Users/brianadams/school/trial/Folder2/FF-15', and so on.

I want to delete folder FF-15 if it is empty from all the Folders.

I tried the following:

import glob
import os 
path = glob.glob('/Users/brianadams/school/trial/**/FF-15')
os.removedirs(path)

But it throws up an error or does not end up deleting the file.

>Solution :

You need to iterate through each file directory for this to work. You can’t delete them from all at once. Slightly modified code, this should work for you.

import glob
import os

ff15_dirs = glob.glob('/Users/brianadams/school/trial/**/FF-15', recursive=True)

for ff15_dir in ff15_dirs:
    if not os.listdir(ff15_dir):
        os.rmdir(ff15_dir)

Edit: Works, I just tested it with a file directory I created using your constraints.

Leave a ReplyCancel reply