How to walk up parent directories?

Ben Finney ben+python at benfinney.id.au
Mon May 4 03:24:59 CEST 2009


Matthew Wilson <matt at tplus1.com> writes:

> Is there already a tool in the standard library to let me walk up from
> a subdirectory to the top of my file system?

Sounds like a pretty seldom-needed task, with an implementation simple
using the existing standard library parts.

> In other words, I'm looking for something like:
> 
>     >>> for x in walkup('/home/matt/projects'):
>     ...     print(x)
>     /home/matt/projects
>     /home/matt
>     /home
>     /

    >>> import os.path
    >>> def walkup(path):
    ...     at_top = False
    ...     while not at_top:
    ...         yield path
    ...         parent_path = os.path.dirname(path)
    ...         if parent_path == path:
    ...             at_top = True
    ...         else:
    ...             path = parent_path
    ... 
    >>> for dir in walkup('/home/matt/projects'):
    ...     print dir
    ... 
    /home/matt/projects
    /home/matt
    /home
    /

> I know I could build something like this with various os.path
> components, but I'm hoping I don't have to.

Not every simple function belongs in the standard library :-)

-- 
 \        “Ubi dubium, ibi libertas.” (“Where there is doubt, there is |
  `\                                                        freedom.”) |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list