How to walk up parent directories?
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)
>>> 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
... path = parent_path
>>> for dir in walkup('/home/matt/projects'):
... print dir
> 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.”) |
More information about the Python-list