How to extract a part of the file path (a directory) in Python?

PythonServer Side ProgrammingProgramming

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

from pathlib import Path
This will give the output:

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.

For example

import os
print(os.path.abspath(os.path.join('/home/username', '..')))
This will give the output:
Updated on 16-Dec-2019 07:02:10