Parsing a path to components

Mark Tolonen M8R-yfto6h at mailinator.com
Sat Jun 7 10:19:42 EDT 2008


"eliben" <eliben at gmail.com> wrote in message 
news:e5fd542f-56d2-4ec0-a3a7-aa1ee106c624 at a70g2000hsh.googlegroups.com...
> On Jun 7, 10:15 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>> On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote:
>> > 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)
>>
>> Won't work for platforms with more than one path separator and if a
>> separator is repeated.  For example r'\foo\\bar/baz//spam.py' or:
>>
>> In [140]: os.path.split('foo//bar')
>> Out[140]: ('foo', 'bar')
>>
>> In [141]: 'foo//bar'.split(os.sep)
>> Out[141]: ['foo', '', 'bar']
>>
>> Ciao,
>>         Marc 'BlackJack' Rintsch
>
> 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']

-Mark 




More information about the Python-list mailing list