1

What is the most pythonic way to test whether a folder, its subfolders, all their subfolders, etc. are empty? I am aware of os.listdir() and have come up with the function below, but it seems that there would be a standard function for this already (though several searches turned up nothing).

def is_empty(target_folder): #Recursively tests whether a folder is empty.
    import os
    if [i for i in os.listdir(target_folder) if not 
    os.path.isdir(os.path.join(target_folder,i))]:
        return False
    else:
        return all([is_empty(os.path.join(target_folder,i)) for i in 
        os.listdir(target_folder) if 
        os.path.isdir(os.path.join(target_folder,i))])
amateur3057
  • 345
  • 1
  • 2
  • 11

1 Answers1

1

You can use os.walk, which does the recursion for you.

That function generates a series of 3-tuples. The first item of that tuple is the name of a folder (directory) under the one you sent the function (starting with the one you passed). The other two items are lists of the subfolders and files directly in the folder of the first item.

So just call os.walk and iterate through the generated triples. Any tuple that has empty lists for the second and third items holds the name of an empty folder name as the first item.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50