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.
# Python program to demonstrate# os.pardir import os # prints .. by defaultprint(os.pardir) |
Output:
..
Example 2: Let’s print the parent of current working directory.
# Python program to demonstrate# os.pardir import os # current working directorypath = os.getcwd()print("Current Directory:", path) # parent directoryparent = os.path.join(path, os.pardir) # prints parent directoryprint("\nParent Directory:", os.path.abspath(parent)) |
Output:
Current Directory: /home/Lazyroar/Desktop/gfg Parent Directory: /home/Lazyroar/Desktop
Example 3: Getting the parent of specified path.
# Python program to demonstrate# os.pardir import os # pathpath = "your/path/for/parent/directory"print("Path:", path) # parentparent = os.path.join(path, os.pardir) # prints the relative file path # for the current directory (parent)print("\nParent:", os.path.relpath(parent)) |
Output:
Path: your/path/for/parent/directory Parent: your/path/for/parent
