Parsing a path to components

Scott David Daniels Scott.Daniels at Acm.Org
Tue Jun 10 08:55:12 EDT 2008


eliben wrote:
... a prety good try ...
> def parse_path(path):
>     """..."""
By the way, the comment is fine.  I am going for brevity here.
>     lst = []
>     while 1:
>         head, tail = os.path.split(path)
>         if tail == '':
>             if head != '': lst.insert(0, head)
>             break
>         else:
>             lst.insert(0, tail)
>             path = head
>     return lst
> ----------------------------------
> 
> Did I miss something and there is a way to do this standardly ?
Nope, the requirement is rare.

> Is this function valid, or will there be cases that will confuse it ?
     parse_path('/a/b/c//d/')

Try something like:
     def parse_path(path):
         '''...same comment...'''
         head, tail = os.path.split(path)
         result = []
         if not tail:
             if head == path:
                 return [head]
             # Perhaps result = [''] here to an indicate ends-in-sep
             head, tail = os.path.split(head)
         while head and tail:
             result.append(tail)
             head, tail = os.path.split(head)
         result.append(head or tail)
         result.reverse()
         return result

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list