Parsing a path to components

eliben eliben at gmail.com
Sat Jun 7 01:55:03 EDT 2008


Hello,

os.path.split returns the head and tail of a path, but what if I want
to have all the components ? I could not find a portable way to do
this in the standard library, so I've concocted the following
function. It uses os.path.split to be portable, at the expense of
efficiency.

----------------------------------
def parse_path(path):
    """ Parses a path to its components.

        Example:
            parse_path("C:\\Python25\\lib\\site-packages\
\zipextimporter.py")

            Returns:
            ['C:\\', 'Python25', 'lib', 'site-packages',
'zipextimporter.py']

        This function uses os.path.split in an attempt to be portable.
        It costs in performance.
    """
    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 ?
Is this function valid, or will there be cases that will confuse it ?

Thanks in advance
Eli



More information about the Python-list mailing list