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.

Asked By: Mridang Agarwalla



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', '..'))
Answered By: Dan Menes

Python 3.4

Use the pathlib module.

from pathlib import Path
path = Path("/here/your/path/file.txt")

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.

Answered By: kender
import os
p = os.path.abspath('..')

C:Program Files —> C:\

C: —> C:\

Answered By: ivo

Using os.path.dirname:

>>> os.path.dirname(r'C:Program Files')
>>> os.path.dirname('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).

Answered By: Wai Yip Tung
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.

Answered By: Eros Nikolli
import os
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 "------------------------------------------------------------"
Answered By: Grandpapa

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

Get Parent Directory Path


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'))
Answered By: Jaykumar Patel

>>> 'D:Dir1'

So a .. helps

import os.path

Answered By: Washington Botelho

An alternate solution of @kender

import os

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))     => '/'
Answered By: benjarobin

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
>>> q.resolve()

Querying path properties:

>>> q.exists()
>>> q.is_dir()

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:


Answered By: 8bitjunkie

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

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

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

>>> input1 = "../data/replies/"

would output,

>>> os.path.dirname(input1)

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

Answered By: samsamara
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))
Answered By: fuyunliu
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))
Answered By: Miguel Mota
>>> 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:WINDOWSsystem32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'

Both examples tried in Python 2.7

Answered By: Soumendra

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))
Answered By: MPA

Suppose we have directory structure like



We want to access the path of “P” from the directory R then we can access using

ROOT = os.path.abspath(os.path.join("..", os.pardir));



We want to access the path of “Q” directory from the directory R then we can access using

ROOT = os.path.abspath(os.path.join(".", os.pardir));
Answered By: Rakesh Chaudhari

To find the parent of the current working directory:

import pathlib
Answered By: Ondrej Sotolar
import os 

def parent_directory():
  # Create a relative path to the parent of the current working directory 
  relative_parent = os.path.join(os.getcwd(), "..") # .. means parent directory

  # Return the absolute path of the parent directory
  return os.path.abspath(relative_parent)

Answered By: Nava Bogatee
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.