To get the parent directory of a file or directory in Python we can use modules os or pathlib:

  • os.path
  • Path(file_path).parent
    • path.parent.absolute()

You can also find how to: change current directory to parent in Python.

We will try to answer on those questions:

  • How do I go to the parent directory path in Python?
  • How do I find the main directory path in Python?

get parent folder with os

import os

file_path = '/home/user/Downloads/test'
parent_directory = os.path.dirname(file_path)

the result is:


The same works for a file input:

file_path = '/home/user/Downloads/test.txt'

the result is:


parent folder name from path

As alternative we can use module pathlib and class Path to get parent folder of file or directory in Python:

from pathlib import Path
file_path = '/home/user/Downloads/ips'
path = Path(file_path)

the result is:


if we try to get only the parent as below:

from pathlib import Path

we will get the parent as PosixPath:


Get parent of CWD working dir

To get the parent of the current working folder CWD we can use - os.path.abspath('..'):

import os

The result is the parent of the working script:


To find the CWD we can use the following code: