In Python, the os module provides several functions for working with files and directories. One common task when working with directories is to obtain the parent directory of the current working directory. In this blog post, we will explore different ways to achieve this in Python.
Before we dive into obtaining the parent directory, let's briefly review the os module. This module provides a way to interact with the operating system in a platform-independent manner. It allows us to perform various file and directory operations such as creating, deleting, renaming, and listing directories, as well as getting information about files and directories, among other things.
Let us now review two ways to use the os module to find the parent directory path in Python!
Method 1: Use os.pardir
The os.pardir is a constant string used by the operating system to refer to the parent directory. This sounds simple enough! Let us see how that works!
If we run this program:
Big deal - that is not so useful! Of course the parent directory is denoted by “..” but that is the relative path. What we are looking for is the absolute path. So what we need to do is to “join” the current working directory with this “..” part, and then find the absolute version of that path. Here is a program to do just that:
Let us unpack how this works. First we find the current working directory (which is not the parent directory, but one step below the parent directory). This is stored in variable “cwd”. We then “join” pardir (which is “..”) to the “cwd” variable and find the absolute pathname of that using the os.path.abspath() function. Thus, we obtain “/home/runner” which is one step above the current directory and thus what we are looking for.
Method 2: Use os.dirname()
You will be happy to note that there is a method in the os module that directly finds the parent directory for us which is os.dirname(). Here is how we can use it:
Notice how much more simple this program is? We just have to pass on the present working directory to dirname(). The output is as before:
In conclusion, we have seen two different ways to obtain the parent directory of the current working directory in Python using the os.path module. Both methods are valid and produce the same result, but the second one is more succinct.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.