Search code examples
pythondirectory

Check if a given directory contains any directory in python


Essentially, I'm wondering if the top answer given to this question can be implemented in Python. I am reviewing the modules os, os.path, and shutil and I haven't yet been able to find an easy equivalent, though I assume I'm just missing something simple.

More specifically, say I have a directory A, and inside directory A is any other directory. I can call os.walk('path/to/A') and check if dirnames is empty, but I don't want to make the program go through the entire tree rooted at A; i.e. what I'm looking for should stop and return true as soon as it finds a subdirectory.

For clarity, on a directory containing files but no directories an acceptable solution will return False.


Solution

  • maybe you want

    def folders_in(path_to_parent):
        for fname in os.listdir(path_to_parent):
            if os.path.isdir(os.path.join(path_to_parent,fname)):
                yield os.path.join(path_to_parent,fname)
    
    print(list(folders_in("/path/to/parent")))
    

    this will return a list of all subdirectories ... if its empty then there are no subdirectories

    or in one line

    set([os.path.dirname(p) for p in glob.glob("/path/to/parent/*/*")])
    

    although for a subdirectory to be counted with this method it must have some file in it

    or manipulating walk

    def subfolders(path_to_parent):
         try:
            return next(os.walk(path_to_parent))[1]
         except StopIteration:
            return []