Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.
C:\Program Files ---> C:\
C:\ ---> C:\
If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple but I couldn't dig it up through Google.
import os.path print os.path.abspath(os.path.join(yourpath, os.pardir))
yourpath is the path you want the parent for.
>>> os.path.dirname(r'C:\Program Files') 'C:\\' >>> os.path.dirname('C:\\') 'C:\\' >>>
os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender's answer using