How get parent directory from file path in Python

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)
print(parent_directory)

the result is:

/home/user/Downloads

The same works for a file input:

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

the result is:

/home/user/Downloads

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)
print(path.parent.absolute())

the result is:

/home/user/Downloads

if we try to get only the parent as below:

from pathlib import Path
Path(file_path).parent

we will get the parent as PosixPath:

PosixPath('/home/user/Downloads')

Get parent of CWD working dir

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

import os
os.path.abspath('..')

The result is the parent of the working script:

'/python/Notebooks'

To find the CWD we can use the following code:

os.getcwd()

result:

'/python/Notebooks/tmp'