How do I get the parent directory in Python?

StackOverflow

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 rating: 611

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.

Answer rating: 353

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 rating: 133

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




Tutorials