How to check if a given directory contains any other directory in Python?



To check if a directory contains any directory or not, simply check the reverse, ie, if it contains any entry that is not a file using the isfile method.

For example

import os
list_dir = os.listdir('.')
for f in list_dir:
    if not os.path.isfile(os.path.join('.', f)):
        print("Not a file")

You can also use the all built in to check this.

For example

import os
list_dir = [os.path.isfile(os.path.join('.', f)) for f in os.listdir('.')]
print(all(list_dir))

The all function will return true only if all entries are files in the given directory.


Advertisements