Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove subfolders with the same name if empty

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading