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?

os.path.dirname(__file__) returns empty

2 answers

I want to get the path of the current directory under which a .py file is executed.

For example a simple file D: est.py with code:

import os

print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)

It is weird that the output is:

D:
test.py
D:	est.py
EMPTY

I am expecting the same results from the getcwd() and path.dirname().

Given os.path.abspath = os.path.dirname + os.path.basename, why

os.path.dirname(__file__)

returns empty?

174

Answer #1

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

os.path.dirname(filename) + os.path.basename(filename) == filename

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use

os.path.dirname(os.path.abspath(__file__))

What is the difference between os.path.basename() and os.path.dirname()?

2 answers

What is the difference between os.path.basename() and os.path.dirname()?

I already searched for answers and read some links, but didn"t understand. Can anyone give a simple explanation?

158

Answer #1

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of "/foo/bar/item" is "/foo/bar".

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of "/foo/bar/item" returns "item"

From: http://docs.python.org/3/library/os.path.html#os.path.basename

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

Want to excel in Python? See our review of the best Python online courses 2022. 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:



Javier Schteiner

Massachussetts | 2022-11-30

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. Will use it in my bachelor thesis

Javier Jackson

Moscow | 2022-11-30

Thanks for explaining! I was stuck with Get parent of current directory using Python for some hours, finally got it done 🤗. Will get back tomorrow with feedback

Ken Krasiko

New York | 2022-11-30

Simply put and clear. Thank you for sharing. Get parent of current directory using Python and other issues with system was always my weak point 😁. I am just not quite sure it is the best method

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

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

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 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

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

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