Here is another relatively simple solution that:
dirname()
(which does not work as expected on one level arguments like "file.txt" or relative parents like "..")abspath()
(avoiding any assumptions about the current working directory) but instead preserves the relative character of pathsit just uses normpath
and join
:
def parent(p):
return os.path.normpath(os.path.join(p, os.path.pardir))
# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/',
'dir/file.txt', '../up/', '/abs/path']:
print parent(p)
Result:
.
foo/bar
with/trailing
dir
..
/abs