Python Split path recursively

path, python, recursion, split, tuples

Solution

Something like this

>>> import os
>>> s = "E:/John/2012/practice/question11"
>>> os.path.split(s)
('E:/John/2012/practice', 'question11')

Notice `os.path.split()` doesn't split up the whole path as `str.split()` would

>>> def rec_split(s):
...     rest, tail = os.path.split(s)
...     if rest == '':
...         return tail,
...     return rec_split(rest) + (tail,)
...
>>> rec_split(s)
('E:', 'John', '2012', 'practice', 'question11')

Edit: Although the question was about Windows paths. It's quite easy to modify it for unix/linux paths including those starting with "/"

>>> def rec_split(s):
...     rest, tail = os.path.split(s)
...     if rest in ('', os.path.sep):
...         return tail,
...     return rec_split(rest) + (tail,)

Problem

I am trying to split a path given as a string into sub-parts using the "/" as a delimiter recursively and passed into a tuple. For ex: "E:/John/2012/practice/question11" should be ('E:', 'John', '2012', 'practice', 'question11'). So I've passed every character excluding the "/" into a tuple but it is not how I wanted the sub-parts joint as displayed in the example. This is a practice question in homework and would appreciate help as I am trying to learn recursion. Thank You so much

Original source