How do I get the parent directory in Python?

Python

Python Problem Overview


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 Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

###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')
>>> https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve">q.resolve()</a>
PosixPath('/etc/rc.d/init.d/halt')

Querying path properties:

>>> https://docs.python.org/3/library/pathlib.html#pathlib.Path.exists">q.exists()</a>
True
>>> https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_dir">q.is_dir()</a>
False

Solution 4 - Python

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

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

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

Solution 5 - Python

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

Solution 6 - Python

os.path.split(os.path.abspath(mydir))[0]

Solution 7 - Python

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

Solution 8 - Python

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

Solution 9 - Python

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

Solution 10 - Python

Suppose we have directory structure like

1]

/home/User/P/Q/R

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

2]

/home/User/P/Q/R

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

Solution 11 - Python

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:

os.path.split(os.path.dirname(currentDir))[1]

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

The above command will return:

myfile

Solution 12 - Python

import os

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

Solution 13 - Python

import os.path

os.path.abspath(os.pardir)

Solution 14 - Python

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.

Solution 15 - Python

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.

Solution 16 - Python

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

Solution 17 - Python

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

>>> 'D:\Dir1'

So a .. helps

Solution 18 - Python

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

Solution 19 - Python

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

Solution 20 - Python

To find the parent of the current working directory:

import pathlib
pathlib.Path().resolve().parent

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMridang AgarwallaView Question on Stackoverflow
Solution 1 - PythonkenderView Answer on Stackoverflow
Solution 2 - PythonWai Yip TungView Answer on Stackoverflow
Solution 3 - Pythonhostingutilities.comView Answer on Stackoverflow
Solution 4 - PythonivoView Answer on Stackoverflow
Solution 5 - PythonbenjarobinView Answer on Stackoverflow
Solution 6 - PythonDan MenesView Answer on Stackoverflow
Solution 7 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 8 - PythonGrandpapaView Answer on Stackoverflow
Solution 9 - PythonSoumendraView Answer on Stackoverflow
Solution 10 - PythonRakesh ChaudhariView Answer on Stackoverflow
Solution 11 - Python8bitjunkieView Answer on Stackoverflow
Solution 12 - PythonMiguel MotaView Answer on Stackoverflow
Solution 13 - PythonWashington BotelhoView Answer on Stackoverflow
Solution 14 - PythonEros NikolliView Answer on Stackoverflow
Solution 15 - PythonsamsamaraView Answer on Stackoverflow
Solution 16 - PythonJaykumar PatelView Answer on Stackoverflow
Solution 17 - PythonArindam RoychowdhuryView Answer on Stackoverflow
Solution 18 - PythonfuyunliuView Answer on Stackoverflow
Solution 19 - PythonMPAView Answer on Stackoverflow
Solution 20 - PythonOndrej SotolarView Answer on Stackoverflow