How do I get the parent directory in Python?


In Python 3.4+ you can use the pathlib module to get the parent directory.

Example

from pathlib import Path
print(Path('/home/username').parent)

Output

This will give the output:

/home

In older versions, you can call the os.path.join on your path and '..'(represents parent directory) and then find its absolute path using os.path.abspath.

Example

import os
print(os.path.abspath(os.path.join('/home/username', '..')))

Output

This will give the output:

/home

Updated on: 16-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements