How do I get the path of the Python script I am running in?
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()
:
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:
This function returns the canonical path of the script, which translates in human-speak to the 'real' file location, not a symbolic link.
Cross-OS compatibility and handling symlinks
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]
.
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:
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.
Was this article helpful?