Python function to extract multiple segments of a file path
Question: I would like to write a Python function that is capable of taking a file path,
like:

> /abs/path/to/my/file/file.txt

And returning three string variables:

  * `/abs` \- the root directory, plus the "top-most" directory in the path
  * `file` \- the "bottom-most" directory in the path; the parent of `file.txt`
  * `path/to/my` \- everything in between the top- and bottom-most directories in the path

So something with the following pseudo-code:

    
    
    def extract_path_segments(file):
        absPath = get_abs_path(file)
        top = substring(absPath, 0, str_post(absPath, "/", FIRST))
        bottom = substring(absPath, 0, str_post(absPath, "/", LAST))
        middle = str_diff(absPath, top, bottom)
    
        return (top, middle, bottom)
    

Thanks in advance for any help here!


Answer: You are looking for [`os.sep`](http://docs.python.org/library/os.html#os.sep),
together with various `os.path` module functions. Simply split the path by
that character, then re-assemble the parts you want to use. Something like:

    
    
    import os
    
    def extract_path_segments(path, sep=os.sep):
        path, filename = os.path.split(os.path.abspath(path))
        bottom, rest = path[1:].split(sep, 1)
        bottom = sep + bottom
        middle, top = os.path.split(rest)
        return (bottom, middle, top)
    

This does _not_ deal very well with Windows paths, where both `\` _and_ `/`
are legal path separators. In that case you _also_ have a drive letter, so
you'd have to special-case that as well anyway.

Output:

    
    
    >>> extract_path_segments('/abs/path/to/my/file/file.txt')
    ('/abs', 'path/to/my', 'file')
    

