How do I get the parent directory in Python?

How do I get the parent directory in 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.

Using os.path.dirname:

>>> os.path.dirname(rC: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. @kenders answer using os.path.join(yourpath, os.pardir).

How do I get the parent directory in 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 dont 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. Ive 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

Leave a Reply

Your email address will not be published.