Use os.getcwd() and __file__ with os.path or pathlib
To determine both the current working directory and the script’s file location:

1. Get the current directory (where the script is run from):

import os
cwd = os.getcwd()
print("Current working directory:", cwd)

2. Get the directory where the Python file itself is located:

import os
script_dir = os.path.dirname(os.path.abspath(__file__))
print("Directory of the script file:", script_dir)

Example:

import os
print("Current working directory:", os.getcwd())
print("Directory of this script file:", os.path.dirname(os.path.abspath(__file__)))

Using pathlib (Python 3.4+ alternative):

from pathlib import Path
cwd = Path.cwd()
script_dir = Path(__file__).resolve().parent
print("Current working directory:", cwd)
print("Directory of the script file:", script_dir)

Notes:

  • os.getcwd() gives you the directory where the Python process was started (the shell’s location).
  • __file__ gives you the path of the script file being executed.
  • Use Path(__file__).resolve().parent for a cleaner and more modern way with pathlib.

Need Help With Python Development?

Work with our skilled Python developers to accelerate your project and boost its performance.

Hire Python Developers

Support On Demand!

Related Q&A