Parsing a path to components

s0suk3 at gmail.com s0suk3 at gmail.com
Sat Jun 7 08:57:03 CEST 2008


On Jun 7, 12:55 am, eliben <eli... at gmail.com> wrote:
> 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 ?
>

You can just split the path on `os.sep', which contains the path
separator of the platform on which Python is running:

components = pathString.split(os.sep)

Sebastian




More information about the Python-list mailing list