December 23, 2021

How to get the current file’s directory in python

This is one of those things I continuously look up; like centering a div.

When I’m working with the file system in python, I often need to open a file or directory relative to the file I’m currently writing my code in. Here’s the code I like to use:

os.path.dirname(os.path.realpath(__file__))

What's the problem?

Lets assume we have a directory with a structure like this:

  • root_directory
    • images_directory
    • get_images.py

If I simply referenced the images_directory as a string, depending on where I am in the filesystem when I call get_images.py, the path may not be correct.

# This will work
cd root_directory && python3 get_images.py

# This wont
python3 root_directory/get_images.py

How to fix it

We first need to get the absolute path of the root_directory in the get_images.py script, which we can do like this:

import os

# returns the directory of this exact python file defining it
root_directory = os.path.dirname(os.path.realpath(__file__))

Once we have that, we can use os.path.join to connect it to our images directory

import os

# returns the directory of this exact python file defining it
root_directory = os.path.dirname(os.path.realpath(__file__))
images_dir = os.path.join(root_directory, 'images_directory')

You can wrap it in a function for good measure

def get_dir_path(dir_name):
    """Returns the full path to the directory provided"""
    parent = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(parent, dir_name)

images_dir = get_dir_path('images_directory')

and that’s it! Now no matter where we call get_images.py from, it’ll work.

# This works
python3 root_directory/get_images.py

# This works too
cd root_directory && python3 get_images.py
Let's Work Together

I solve problems with DevOps, Developer Relations, IoT, and Artificial Intelligence.