split a directory string into a list

Duncan Booth duncan.booth at invalid.invalid
Fri Feb 25 10:30:35 EST 2005


Michael Maibaum wrote:

> On 25 Feb 2005, at 14:09, Harper, Gina wrote:
> 
>> I would start with something like this:
>> somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/'
>> somelist = somestring.split('/')
>> print somelist
> 
> However - this will not work on Windows. It'd work on all the OS I 
> usually use though ;)
> 

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.



More information about the Python-list mailing list