split a directory string into a list

Josef Meile jmeile at hotmail.com
Fri Feb 25 13:24:26 EST 2005


Hi Duncan,

> This should work reasonably reliably on Windows and Unix:
> 
> 
>>>>somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/'
>>>>os.path.normpath(somestring).split(os.path.sep)
> 
> ['', 'foo', 'bar', 'beer', 'sex', 'cigarettes', 'drugs', 'alcohol']
> 
> However a better solution is probably to call os.path.split repeatedly 
> until it won't split anything more:
> 
> 
>>>>somestring = r'C:\foo\bar\beer'
>>>>def splitpath(p):
> 
> 	res = []
> 	while 1:
> 		p, file = os.path.split(p)
> 		if not file:
> 			break
> 		res.append(file)
> 	res.append(p)
> 	res.reverse()
> 	return res
> 
> 
>>>>splitpath(somestring)
> 
> ['C:\\', 'foo', 'bar', 'beer']
> 
>>>>splitpath('foo/bar')
> 
> ['', 'foo', 'bar']
> 
> The first component is an empty string for relative paths, a drive letter 
> or \ for absolute Windows paths, \\ for UNC paths, / for unix absolute 
> paths.

I don't understand why the second approach is better than the first
one. In my opinion it is the contrary:

On the first approach, you only scan the string twice:
when you do "os.path.normpath(somestring)" and finally when splitting
the string. On the other hand, the second approach goes through the
string several times, when doing the os.path.split. Finally when doing
the res.reverse(). Or am I wrong? I also saw you said:
"This should work ***reasonably*** reliably on Windows and Unix". Are
there any cases when it does not work?

Regards,
Josef



More information about the Python-list mailing list