Question :
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.
Answer #1:
Update from Python 3.4
Use the pathlib
module.
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)
Old answer
Try this:
import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath
is the path you want the parent for.
Answer #2:
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)
.
Answer #3:
The Pathlib method (Python 3.4+)
from pathlib import Path
Path('C:Program Files').parent
# Returns a Pathlib object
The traditional method
import os.path
os.path.dirname('C:Program Files')
# Returns a string
Which method should I use?
Use the traditional method if:
-
You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)
-
Your Python version is less than 3.4.
-
You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.
If none of the above apply, use Pathlib.
What is Pathlib?
If you don’t know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I’ve highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.
Navigating inside a directory tree:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
Querying path properties:
>>> q.exists()
True
>>> q.is_dir()
False
Answer #4:
import os
p = os.path.abspath('..')
C:Program Files
—> C:\
C:
—> C:\
Answer #5:
An alternate solution of @kender
import os
os.path.dirname(os.path.normpath(yourpath))
where yourpath
is the path you want the parent for.
But this solution is not perfect, since it will not handle the case where yourpath
is an empty string, or a dot.
This other solution will handle more nicely this corner case:
import os
os.path.normpath(os.path.join(yourpath, os.pardir))
Here the outputs for every case that can find (Input path is relative):
os.path.dirname(os.path.normpath('a/b/')) => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/b')) => 'a'
os.path.normpath(os.path.join('a/b', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/')) => ''
os.path.normpath(os.path.join('a/', os.pardir)) => '.'
os.path.dirname(os.path.normpath('a')) => ''
os.path.normpath(os.path.join('a', os.pardir)) => '.'
os.path.dirname(os.path.normpath('.')) => ''
os.path.normpath(os.path.join('.', os.pardir)) => '..'
os.path.dirname(os.path.normpath('')) => ''
os.path.normpath(os.path.join('', os.pardir)) => '..'
os.path.dirname(os.path.normpath('..')) => ''
os.path.normpath(os.path.join('..', os.pardir)) => '../..'
Input path is absolute (Linux path):
os.path.dirname(os.path.normpath('/a/b')) => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir)) => '/a'
os.path.dirname(os.path.normpath('/a')) => '/'
os.path.normpath(os.path.join('/a', os.pardir)) => '/'
os.path.dirname(os.path.normpath('/')) => '/'
os.path.normpath(os.path.join('/', os.pardir)) => '/'
Answer #6:
os.path.split(os.path.abspath(mydir))[0]
Answer #7:
os.path.abspath(os.path.join(somepath, '..'))
Observe:
import posixpath
import ntpath
print ntpath.abspath(ntpath.join('C:\', '..'))
print ntpath.abspath(ntpath.join('C:\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))
Answer #8:
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"