split a directory string into a list

Duncan Booth duncan.booth at invalid.invalid
Sat Feb 26 06:09:22 EST 2005


Josef Meile wrote:

> "This should work ***reasonably*** reliably on Windows and Unix". Are
> there any cases when it does not work?

The most obvious case where it wouldn't work would be for a UNC path name. 
Using the string split method gives two empty strings:

>>> os.path.normpath(r'\\machine\share').split(os.path.sep)
['', '', 'machine', 'share']
>>> 


whereas the splitpath function I proposed gives you:

>>> splitpath(r'\\machine\share')
['\\\\', 'machine', 'share']

So to find out the type of path (relative, absolute, unc), you only have to 
consider the first element with my function but you have to look at the 
first two elements if you just naively split the string.

Also a relative windows path with a drive letter doesn't get fully split:

>>> os.path.normpath(r'c:dir\file').split(os.path.sep)
['c:dir', 'file']
>>> splitpath(r'c:dir\file')
['c:', 'dir', 'file']

If you really are worried about speed (and are sure you aren't optimising 
prematurely), then you could combine some special case processing near the 
start of the string with a simple split of the remainder.



More information about the Python-list mailing list