Search code examples
pythonregex

Find root of path


I have a path:

path = foo/bar/baz

and I would like to determine what the base is. In this example it should return "foo".

There are a few ways I have tried:

root = re.search('(.+?)/(.+)', path).group(1)

paths = path.split('/')[0]
root = paths[0] if paths[0] or len(paths) <= 1 else '/'.join(paths[0:2])

def rootname(path):
  head,tail = os.path.split(path)
  if head != '':
   return rootname(head)
  else:
   return path
root = rootname(path)

Is there a more 'Pythonic' way to access the root directory?

i.e.

root = os.path.''rootname''(path)

Solution

  • If you're looking for a built-in or stdlib function that does exactly what you want, there is none.

    If you're looking for a third-party library, try searching PyPI and ActiveState. You'll find path-manipulation libraries like pathlib (that has been included since Python 3.4), Unipath and forked-path (both based on an earlier library, a modified version of which was considered but never accepted for inclusion in Python 2), and dozens more. (Or, if you're using a framework like twisted or PyQt, it may come with one built in.)

    Using such a library, you can generally get the root path in one line, like:

    pathlib.Path(mypath).parts[0]
    Unipath.Path(mypath).split_root()[0]
    Unipath.Path(mypath).components()[0]
    path.path(mypath).splitall()[0]
    

    Their definition of "root" might not be exactly the same as yours. (As J.F. Sebastian points out, we don't actually know exactly what your definition of "root" is, so it's hard to guess whether it will match…) So, you might still need this kind of code:

    components = path.path(mypath).splitall()[0]
    return components[0] if len(components[0]) > 1 else components[0]/components[1]
    

    But regardless, it'll be better than doing regexps and string manipulation.

    (In fact, even if you don't use a third-party library, you should try to build everything out of os.path functions instead of string functions—that way, when you try it on Windows next year, there's a good chance it'll work out of the box, and if not it'll probably require only minor changes, as opposed to being absolutely guaranteed it won't work and might need a complete rewrite.)