Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Import from sibling directory
Next article icon

Get parent of current directory using Python

Last Updated : 13 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, OS module is used to interact with the operating system. It comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. 
OS module provides various ways for getting the parent directory. Some of the ways are: 

  • Using os.path.abspath() 
  • Using os.path.dirname() 
  • Using os.path.relpath() and os.path.dirname()
  • Using Path().resolve().parent

Using os.path.abspath() to get parent of current directory

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 the help of os.path.join() and os.pardir(). 
os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put 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: 

Python3




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

Output:  

 

Using os.path.dirname() to get parent of current directory

os.path.dirname() method in Python is used to get the directory name from the specified path. 

Syntax: os.path.dirname(path)
Parameter: 
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:  

Python3




# Python program to get parent
# directory
 
 
import os
 
# get current directory
path = os.getcwd()
print("Current Directory", path)
print()
 
# parent directory
parent = os.path.dirname(path)
print("Parent directory", parent)
 
 

Output: 

 

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

In the above examples, getting the parent directory was limited to one level, i.e. we were only able to get the parent of current directory upto one level only. Suppose we want to find the parent to the parent directory, then the above code fails. This can be achieved by using os.path.relpath() and os.path.dirname() together. 
os.path.relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from 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.

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

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

Example:

Python3




# Python program to get the
# parent directory
 
 
import os.path
 
# function to get parent
def getParent(path, levels = 1):
    common = path
 
    # Using for loop for getting
    # starting point required for
    # os.path.relpath()
    for i in range(levels + 1):
 
        # Starting point
        common = os.path.dirname(common)
 
    # Parent directory upto specified
    # level
    return os.path.relpath(path, common)
 
path = 'D:/Pycharm projects / GeeksforGeeks / Nikhil / gfg.txt'
print(getParent(path, 2))
 
 

Output:

 

Using Path().resolve().parents to get parent of current directory

Syntax: Path(path).resolve().parents[0]

Parameter: 

  • path: path of the file or folder whose parent we want to fetch.

Return Type: It returns WindowsPath.parents object.

Here we are using the path module to get the parent of current directory and instead of parents[0] we can also use parent.parent to fetch the parent of the current directory.

Example:

Python3




from pathlib import Path
 
d = Path("C:\\Users\\DELL\\Downloads").resolve().parents[0]
 
print(d)
 
 

Output:

 



Next Article
Python - Import from sibling directory

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • Python os-module-programs
  • Python OS-path-module
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • Get Current directory in Python
    In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The conce
    3 min read
  • How to Get directory of Current Script in Python?
    A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the current
    4 min read
  • How to Create Directory If it Does Not Exist using Python?
    In this article, We will learn how to create a Directory if it Does Not Exist using Python. Method 1: Using os.path.exists() and os.makedirs() methods Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if
    2 min read
  • Check if directory contains files using python
    Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(
    3 min read
  • Python - Import from sibling directory
    In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree: Directory Tree: root : | |__SiblingA: | \__A.py | |__SiblingB: | \__B.py In B.py we will crea
    3 min read
  • Get Location of Python site-packages Directory
    A Python installation has a site-packages directory inside the module directory. This directory is where user-installed packages are dropped. A .pth file in this directory is maintained, which contains paths to the directories where the extra packages are installed. In this article, you will learn h
    2 min read
  • Python - Import from parent directory
    In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this. In the parent directory, we have a subdirectory, geeks.py file and in th
    5 min read
  • How to print all files within a directory using Python?
    The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python. In this article, we will learn how to
    3 min read
  • How to Get Current Date and Time using Python
    In this article, we will cover different methods for getting data and time using the DateTime module and time module in Python. Different ways to get Current Date and Time using PythonCurrent time using DateTime objectGet time using the time moduleGet Current Date and Time Using the Datetime ModuleI
    6 min read
  • Change current working directory with Python
    The OS module in Python is used for interacting with the operating system. This module comes under Python's standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences