Explain Codes LogoExplain Codes Logo

How do I get the path of the Python script I am running in?

python
file-path
os-path
cross-os-compatibility
Nikita BarsukovbyNikita Barsukov·Oct 17, 2024
TLDR

Here's a quick way to retrieve the path of the currently running Python script using the special attribute __file__ combined with os.path.abspath():

import os print(os.path.abspath(__file__)) # Cheaper than a GPS, huh?

This will do the job by printing out the full, absolute path of the current script.

Deep dive: Understanding __file__ and paths

In Python, __file__ is a built-in attribute that's automatically populated with the pathname from which a module was loaded, hence it would give the relative or absolute path depending on how you ran the script. We use os.path.abspath() to normalize this path into a fully qualified, absolute path.

What if you are dealing with symbolic links? There's os.path.realpath() for that:

import os print(os.path.realpath(__file__)) # Playing hide and seek with symlinks!

This function returns the canonical path of the script, which translates in human-speak to the 'real' file location, not a symbolic link.

We all love when things just work everywhere, don't we? Not everyone codes in the same environment. Ensuring cross-platform compatibility is essential. All os.path functions handle paths universally across macOS, Windows, and Unix/Linux operating systems.

If you want just the directory and not the full file path, you can use os.path.dirname() in combination with sys.argv[0].

import os import sys script_dir = os.path.dirname(os.path.abspath(sys.argv[0])) print(script_dir) # This is me. Well... my directory at least.

Detecting an alternative route

When your code is a packaged application (py2exe, etc), __file__ might not be your hero anymore. For these cases, you could use os.path.dirname(sys.argv[0]) for the rescue:

import os import sys script_path = os.path.dirname(sys.argv[0]) print(os.path.abspath(script_path)) # "Why do we fall, sir? So that we can learn to pick ourselves up." - Alfred, Batman Begins

As suggested by an old, trusted friend— Dive Into Python Chapter 7.2 has more about the behavior of file paths within Python scripts.

Sideways and possible detours

Sometimes, while traveling the codeverse, you might encounter unexpected situations like:

  • If you are running an interactive session or a script is executed from an embedded Python interpreter, __file__ might be undefined.
  • Pay extra attention when the script is executed from a network location (Windows UNC path, NFS mounts, etc.)—things might not work as expected.
  • Remember, when loading from a compiled file, __file__ would end with a .pyc extension.