Find lowest level directory

Peter Otten __peter__ at
Thu Dec 13 16:49:27 CET 2012

loial wrote:

> How can I find the full path of the lowest level directory in a directory
> structure?
> If there is more than one directory at the lowest level, the first one
> found will be enough.

import os

def directories(root):
    for path, folders, files in os.walk(root):
        for name in folders:
            yield os.path.join(path, name)

def depth(path):
    return path.count(os.sep)

some_folder = ...
print max(directories(some_folder), key=depth)

More information about the Python-list mailing list