Find root of path
>>> import os
>>> path = '/foo/bar/baz'
>>> path = path.lstrip(os.sep) # Get rid of leading "/" if any
>>> root = path[:path.index(os.sep)] if os.sep in path else path
>>> root
'foo'
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.)