0

I have an exercise to walk through all direcories in a subdirectory and check if there are empty or not. I already tried something but this don't work:

import os
path = input(">>> ")

for (root,dirs,files) in os.walk(path, topdown=True):
    if len(dirs and files) == 0:
        print(os.listdir(dirs)) == 0
        print(root)
        print(dirs)
        print(files)
        print('--------------------------------')
    else:
        print()

Can you help me with it?

Thanks

leon1912
  • 1
  • 1
  • Have a look into this, https://stackoverflow.com/questions/49284015/how-to-check-if-folder-is-empty-with-python – sushanth Jun 24 '20 at 10:43

1 Answers1

1

You can try this:

'''
    Check if a Directory is empty :
'''    
if len(os.listdir(path) ) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
  • You have to import os
AlexFocus
  • 26
  • 4
  • Thanks for your answer. But is does not run through the other folders in the subdirectory. How can I do that? – leon1912 Jun 24 '20 at 12:15
  • Do you mean immediate subdirectories, or every directory right down the tree? Either way, you could use os.walk to do this: os.walk(directory) will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively. – AlexFocus Jun 24 '20 at 13:21