Search code examples
pythonpathstandard-library

Standard python function to split paths?


NOTE: Please, don't code it for me. I already have a home-rolled function to do what I describe below.

Is there a function in the standard Python library that will take an absolute path as argument, and return a tuple of all its "atomic" path components, after removing all redundant ones (e.g. ./), resolving bits like ../, etc.? For example, given the Unix path /s//pam/../ham/./eggs, the output should be

('/', 's', 'ham', 'eggs')

and given the Windows path C:\s\\pam\..\ham\.\eggs, the output should be

('C:', '\\', 's', 'ham', 'eggs')

Thanks!


Solution

  • as close as you get (AFAIR) with the standard lib:

       >>> import os
       >>> help(os.path.split)
        Help on function split in odule ntpath:
    
        split(p)
            Split a pathname.
            Return tuple (head, tail) where tail is everything after the final slash.
            Either part may be empty.
    

    this does not solve your usecase, but is trivially to extend so it does. For more info, see the comments.