Python – os.pardir() method with example

In Python, OS module provides various functions to interact with the operating system. This module comes under the Python standard utility module, so there is no need to install it manually.

os.pardir is a constant string used by the operating system to refer to the parent directory. This method is also available via os.path.pardir()

Note: os.pardir is ‘.. for UNIX based OS and ‘::‘ for Mac OS.

Syntax: os.pardir

Return type: a string that refers to the parent directory.



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# os.pardir
  
import os
  
# prints .. by default
print(os.pardir)

chevron_right


Output:

..

 
Example 2: Let’s print the parent of current working directory.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# os.pardir
  
  
import os
  
  
# current working directory
path = os.getcwd()
print("Current Directory:", path)
  
# parent directory
parent = os.path.join(path, os.pardir)
  
# prints parent directory
print("\nParent Directory:", os.path.abspath(parent))

chevron_right


Output:

Current Directory: /home/geeks/Desktop/gfg

Parent Directory: /home/geeks/Desktop

 
Example 3: Getting the parent of specified path.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# os.pardir
  
  
import os
  
  
# path
path = "your/path/for/parent/directory"
print("Path:", path)
  
# parent
parent = os.path.join(path, os.pardir)
  
# prints the relative file path 
# for the current directory (parent)
print("\nParent:", os.path.relpath(parent))

chevron_right


Output:

Path: your/path/for/parent/directory

Parent: your/path/for/parent



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nishkarsh146