Parsing a path to components
Duncan Booth
duncan.booth at invalid.invalid
Mon Jun 9 04:12:31 EDT 2008
"Mark Tolonen" <M8R-yfto6h at mailinator.com> wrote:
>> Can you recommend a generic way to achieve this ?
>> Eli
>
>>>> import os
>>>> from os.path import normpath,abspath
>>>> x=r'\foo\\bar/baz//spam.py'
>>>> normpath(x)
> '\\foo\\bar\\baz\\spam.py'
>>>> normpath(abspath(x))
> 'C:\\foo\\bar\\baz\\spam.py'
>>>> normpath(abspath(x)).split(os.sep)
> ['C:', 'foo', 'bar', 'baz', 'spam.py']
That gets a bit messy with UNC pathnames. With the OP's code the double
backslah leadin is preserved (although arguably it has split one time too
many, '\\\\frodo' would make more sense as the first element:
>>> parse_path(r'\\frodo\foo\bar')
['\\\\', 'frodo', 'foo', 'bar']
With your code you just get two empty strings as the leadin:
>>> normpath(abspath(r'\\frodo\foo\bar')).split(os.sep)
['', '', 'frodo', 'foo', 'bar']
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list