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

PythonServer Side ProgrammingProgramming

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.

raja
Published on 27-Dec-2017 10:21:04
Advertisements