Python – Relative Paths In Python (No Easy Way)

One of the most asked thing by Python coders is “Relative Path” .. O’ the relative paths! Especially for those who come from C/C++ or C# backgrounds, I have a bad news for you. “There is no easy way to get the relative path in Python” you can’t use ‘..’ to get to one directory up. The good news is, you can get to that directory but, there is no easy way! Let’s see how to use relative paths and import a module/package from a directory one level up.

Let’s imagine we are working with a folder structure and modules as following..

/root-directory                                 <Root Directory>
               MathFunctions/                   <Child Directory> 
               StringFunctions/                 <Child Directory> 

Now, let’s see how you can import ‘’ from directory ‘StringFunctions’ in ‘’ in directory ‘MathFunctions’. The basic requirement for importing a module or a package into a Python code is, the directory of module or package must be visible to Python. The way to do it is to add the directory in ‘Pythonpath‘.

Everything begins at the root. For Python this root is the current directory or the directory where the module is located. So, we will need to the Full path or Absolute path of the module. The way to it is by using os.path.abspath(__file__)  . So once we have the absolute path of the module we get the absolute directory path of it and then going up the levels using os.path.dirname 

Look at the following code

import sys
import os

absFilePath = os.path.abspath(__file__)
fileDir = os.path.dirname(os.path.abspath(__file__))
parentDir = os.path.dirname(fileDir)

As you can see I have used ‘os.path.dirname’ twice to get to the parent directory of the current directory. When you add this code into ‘’ mentioned above it outputs following lines.

os.path.dirname(os.path.dirname(os.path.abspath(__file__))) is equal to ‘..\’ in C/C++ or C#

So, now that we have reached the parent directory of the directory where the current module lies, let’s think about the other child directory. In the case mentioned above, we want to refer to the in StringFunctions . So, we have to come up with the path for We will use os.path.join to join the directory path and name of the child directory like os.path.join(<directory1>,<directory2>). Once, we have the path to StringFunctions directory we need to add it into Pythonpath using sys.path.append().

Take a look at the code

Relative Paths in Python

So this is how you can get the relative paths in Python. Not really an elegant way but this is the way to do it. Please let me know if this tutorial helped. Also, don’t forget to add your comments/questions in the comments section. Thank you!

One Reply to “Python – Relative Paths In Python (No Easy Way)”

Leave a Reply