|

How to get the full path and directory of a Python script itself?

How to Get the Full Path of a Python Script

When writing scripts that need to load configuration files or assets relative to their own location, you can’t rely on the “current working directory” (.), as that changes depending on how the script was called.

The Modern Way: pathlib (Python 3.4+)

from pathlib import Path

# The directory where the script lives
script_dir = Path(__file__).resolve().parent
print(script_dir)

Why resolve()?

resolve() follows symlinks and removes any .. or . components, giving you the “canonical” absolute path. This is crucial for robust deployment.

Python in 2026

  • __file__ Limitations: Note that __file__ isn’t available in interactive shells or some “frozen” executables (like those made with PyInstaller). In those cases, sys.argv[0] or sys.executable might be better alternatives.
  • Project Structure: Modern Python projects often use pyproject.toml and tools like Poetry or Hatch, which manage paths and dependencies so you rarely need to manually calculate script directories anymore.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *