Tutorial :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:\  


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.


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.


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).


In Python 3.4+

from pathlib import Path  Path('C:\Program Files').parent  

Python documentation

Additional Info

The new pathlib library brings together and simplifies using paths and common file operations. Here are some examples from the docs.

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  


import os  p = os.path.abspath('..')  

C:\Program Files ---> C:\\\

C:\ ---> C:\\\


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))     => '/'  




os.path.abspath(os.path.join(somepath, '..'))  


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', '..'))  


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 "------------------------------------------------------------"  


If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:


i.e. with a currentDir value of /home/user/path/to/myfile/file.ext

The above command will return:



>>> import os  >>> os.path.basename(os.path.dirname(<your_path>))  

For example in Ubuntu:

>>> my_path = '/home/user/documents'  >>> os.path.basename(os.path.dirname(my_path))  # Output: 'user'  

For example in Windows:

>>> my_path = 'C:\WINDOWS\system32'  >>> os.path.basename(os.path.dirname(my_path))  # Output: 'WINDOWS'  

Both examples tried in Python 2.7


print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))  

You can use this to get the parent directory of the current location of your py file.


import os.path    os.path.abspath(os.pardir)  


Just adding something to the Tung's answer (you need to use rstrip('/') to be more of the safer side if you're on a unix box).

>>> input = "../data/replies/"  >>> os.path.dirname(input.rstrip('/'))  '../data'  >>> input = "../data/replies"  >>> os.path.dirname(input.rstrip('/'))  '../data'  

But, if you don't use rstrip('/'), given your input is

>>> input = "../data/replies/"  

would output,

>>> os.path.dirname(input)  '../data/replies'  

which is probably not what you're looking at as you want both "../data/replies/" and "../data/replies" to behave the same way.


import os    dir_path = os.path.dirname(os.path.realpath(__file__))  parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))  


GET Parent Directory Path and make New directory (name new_dir)

Get Parent Directory Path

os.path.abspath('..')  os.pardir  

Example 1

import os  print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))  

Example 2

import os  print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))  


os.path.abspath('D:\Dir1\Dir2\..')    >>> 'D:\Dir1'  

So a .. helps


import os    def parent_filedir(n):      return parent_filedir_iter(n, os.path.dirname(__file__))    def parent_filedir_iter(n, path):      n = int(n)      if n <= 1:          return path      return parent_filedir_iter(n - 1, os.path.dirname(path))    test_dir = os.path.abspath(parent_filedir(2))  


The answers given above are all perfectly fine for going up one or two directory levels, but they may get a bit cumbersome if one needs to traverse the directory tree by many levels (say, 5 or 10). This can be done concisely by joining a list of N os.pardirs in os.path.join. Example:

import os  # Create list of ".." times 5  upup = [os.pardir]*5  # Extract list as arguments of join()  go_upup = os.path.join(*upup)  # Get abspath for current file  up_dir = os.path.abspath(os.path.join(__file__, go_upup))  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »