Search code examples
pythonglob

Check if path is empty in glob?


Check if any folder in the glob search is empty and print their names.

There are some folders that are empty in the directories.

This is the code:

for i in glob.iglob('**/Desktop/testna/**' ,recursive = True):
    if not os.listdir(i): 
        print(f'{i} is empty' + '\n')

Returns:

NotADirectoryError

Solution

  • Finding empty directories is a lot easier with os.walk:

    import os
    print([root for root, dirs, files in os.walk('/') if not files and not dirs])
    

    Or if you prefer to print the files line by line:

    import os
    for root, dirs, files in os.walk('/'):
        if not files and not dirs:
            print(root)