How do I get the full path of the current file's directory?
Want to know where your script lives? Here's how:
Now, current_dir
is your script's home--neat, right? The os.path.realpath()
function even takes care of those pesky symlink paths!
newPathWhoDis: Using pathlib in Python 3
Python 3 introduced a cozier way of finding your script’s path using the pathlib
module:
The resolve()
function is your script's personal GPS, turning relative paths into absolute ones with ease.
The Sneaky __file__
Disclaim-Er! __file__
might be on strike in interactive sessions or packaged Python apps. In such cases, use os.getcwd()
for a quick and dirty file path:
This will give you the path of your current pit stop (working directory), not the address of your scrip-ture.
A buffet of file path options
Method | What You Get | Module | Python Version |
---|---|---|---|
Path(__file__).parent.resolve() | File location service (absolute) | pathlib | 3.x |
os.path.dirname(os.path.abspath(__file__)) | Same as above, just retro | os | 2.x & 3.x |
Path().resolve() | Current pit stop (absolute) | pathlib | 3.x |
os.path.abspath(os.getcwd()) | Same as above, but classic | os | 2.x & 3.x |
Jupyter Path Tricks
Running a Jupyter Notebook? __file__
is taking a nap! Instead, use Path().absolute()
for driving directions:
This returns the path to where your notebook was launched, which could be anywhere!
Going Real with realPath
Did your code make a pit-stop at symlink city? Use os.path.realpath
to find the original path:
source_path
can help your code escape the maze of symlinks and point to its true source path.
Import Tracking
Looking for an imported module's residence? Here is how:
Your __file__
compass now points to your imported module’s local address, cool right?
Old Reliable: The os Approach
Looking for a timeless, tested, and tried approach that ensures cross-compatibility? Keep it classic with os
:
This particular piece of wizardry has been around since the Python 2 days. And it's going nowhere soon.
Quick recap
pathlib
is the suave newcomer in Python 3+ that makes path manipulation classier.os.path
, though vintage, still gets the job done.- Converting
Path
objects to strings is as easy asstr(path)
. .parent
is your script’s lineage and.resolve()
translates relative paths to absolute.
Was this article helpful?