I l@ve RuBoard Previous Section Next Section

4.16 Splitting a Path into All of Its Parts

Credit: Trent Mick

4.16.1 Problem

You want to process subparts of a file or directory path.

4.16.2 Solution

We can define a function that uses os.path.split to break out all of the parts of a file or directory path:

import os, sys
def splitall(path):
    allparts = []
    while 1:
        parts = os.path.split(path)
        if parts[0] == path:  # sentinel for absolute paths
            allparts.insert(0, parts[0])
            break
        elif parts[1] == path: # sentinel for relative paths
            allparts.insert(0, parts[1])
            break
        else:
            path = parts[0]
            allparts.insert(0, parts[1])
    return allparts

4.16.3 Discussion

The os.path.split function splits a path into two parts: everything before the final slash and everything after it. For example:

>>> os.path.split('c:\\foo\\bar\\baz.txt')
('c:\\foo\\bar', 'baz.txt')

Often, it's useful to process parts of a path more generically; for example, if you want to walk up a directory. This recipe splits a path into each piece that corresponds to a mount point, directory name, or file. A few test cases make it clear:

>>> splitall('a/b/c')
['a', 'b', 'c']
>>> splitall('/a/b/c/')
['/', 'a', 'b', 'c', '']
>>> splitall('/')
['/']
>>> splitall('C:')
['C:']
>>> splitall('C:\\')
['C:\\']
>>> splitall('C:\\a')
['C:\\', 'a']
>>> splitall('C:\\a\\')
['C:\\', 'a', '']
>>> splitall('C:\\a\\b')
['C:\\', 'a', 'b']
>>> splitall('a\\b')
['a', 'b']

4.16.4 See Also

Recipe 4.17; documentation on the os.path module in the Library Reference.

    I l@ve RuBoard Previous Section Next Section