How do I get the parent directory in Python?
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:\
and
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.
Python 3.4
Use the pathlib
module.
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
Old answer
Try this:
import os
print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath
is the path you want the parent for.
Using os.path.dirname
:
>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
Caveat: 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 os.path.join(yourpath, os.pardir)
.