Get parent of current directory using Python

| | | | | | | | | | |

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:

Get parent of current directory using Python cwd: Questions

Get parent of current directory using Python dirname: Questions

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

Shop

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

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method