Get parent of current directory using Python

| | | | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

The OS module provides various ways to get the parent directory. Some of the ways:

Using os.path.abspath ()

os.path.abspath () can be used to get the parent directory. This method is used to get the normalized version of the path. This function also needs help os.path.join ( () and os.pardir () .
os.path.join ( () in Python os.path.join ( () combines one or more path components. This method concatenates various path components with exactly one (& # 39; / & # 39;) directory separator after each non-empty part except the last path component. If the last component of the path to join is empty, then the (& # 39; / & # 39;) directory separator is placed at the end.

Syntax: os.path.abspath (path)

Parameters:
path: A path-like object representing a file system path.

Return Type: Returns a string that is a normalized version of the path.

Example:

# Python program to get parent
# directory

import os


# get the current directory

path = os.getcwd ()

print ( "Current Directory" , cwd)


# prints parent directory

print (os.path.abspath ( os.path.join ( (path, os.pardir)))

Output:

Using os.path.dirname ()

os.path.dirname () in Python is used to get the name of a directory at a given path.

Syntax: os.path.dirname(path)

P arameter:
path: A path-like object representing a file system path.

Return Type: This method returns a string value which represents the directory name from the specified path.

Example :

# Python program to get parent
# directory

import os


# get the current directory

path = os.getcwd ()

print ( "Current Dir ectory " , path)

print ( )


# parent directory

parent = os.path.dirname (path)

print ( "Parent directory" , parent)

Exit:

Using os.path.relpath () and os.path.dirname ()

In the examples above, getting the parent directory was limited to one level, that is, we could only get the parent level of the current directory to only one level ... Suppose we want to find the parent for the parent directory, then the above code will fail. This can be achieved by sharing os.path.dirname () .

os.path.relpath () in Python is used to get the relative path to a file at a given path from either the current working directory or the given directory.

Syntax: os.path.relpath (path, start = os.curdir)

Parameter:
path: A path-like object representing the file system path.
start (optional): A path-like object representing the file system path.
The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.

A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the relative file path to given path from the start directory.0222

Example:

To get the parent directory according to user-specified levels, we will create a function getParent () which will accept a path and levels as arguments. Inside the function, the for loop will repeat level + 1 time numbers, and inside the for loop loop, os.path.dirname () will be called. Calling this function inside a for loop will give us a starting point from which os.path.relpath () will give the relative path to the file.

Below is the implementation.

# Python getter
# parent directory

import os.path


# function to get parent

def getParent (path, levels = 1 ):

common = path

# Usage for loop to get

# the starting point required for

# os.path.relpath ()

for i in range (levels + 1 ):

# Starting point

common = os.path.dirname (common)

# Parent directory before the specified

# level

return os.path.relpath (path, common)

path = ’D: / Pycharm projects / Python.Engineering / Nikhil / gfg.txt’

print (getParent (path, 2 ))

Exit:

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Get parent of current directory using Python, check other ast Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Boris Nickolson

Tallinn | 2023-03-22

Simply put and clear. Thank you for sharing. Get parent of current directory using Python and other issues with join was always my weak point 😁. Will get back tomorrow with feedback

Marie Porretti

Massachussetts | 2023-03-22

Thanks for explaining! I was stuck with Get parent of current directory using Python for some hours, finally got it done 🤗. I just hope that will not emerge anymore

Chen Zelotti

Milan | 2023-03-22

I was preparing for my coding interview, thanks for clarifying this - Get parent of current directory using Python in Python is not the simplest one. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically