Question
How can I determine the following in Python?
- The current directory: the folder I was in when I ran the Python script from the shell
- The directory of the Python file being executed: the folder where the script itself is stored
For example, if I run a script from one location but the .py file is saved in another, how can I get both paths correctly?
Short Answer
By the end of this page, you will understand the difference between the current working directory and a script's file location in Python. You will learn which built-in tools to use, how os.getcwd() differs from __file__, when each one matters, and how to avoid common path-related mistakes in real programs.
Concept
In Python, two path concepts are often confused:
- Current working directory (CWD): the directory your process is currently running in
- Script directory: the directory where the Python file is located
These are not always the same.
For example:
- Your script may be stored in
/projects/app/script.py - But you might run it while your shell is in
/home/user
In that case:
- The working directory is
/home/user - The script directory is
/projects/app
This distinction matters because many file operations use the current working directory by default. If your code opens a file like this:
open("data.txt")
Python looks for data.txt relative to the current working directory, not automatically relative to the script file.
How to get each one
To get the current working directory:
import os
print(os.getcwd())
To get the directory of the current script:
import os
print(os.path.dirname(os.path.abspath(__file__)))
Mental Model
Think of it like this:
- The current working directory is your current location
- The script directory is your home address
You might currently be standing in a coffee shop, but your home is somewhere else.
In the same way:
os.getcwd()tells you where the program is currently standing__file__tells you where the script lives
If you ask for a relative file path, Python usually interprets it from where it is standing, not from where the script lives.
That is why beginners often expect this:
open("config.json")
to load a file next to the script, but it actually loads from the current working directory unless you build the path explicitly.
Syntax and Examples
Current working directory
Use os.getcwd():
import os
current_dir = os.getcwd()
print(current_dir)
This returns the directory the Python process is running in.
Script file directory
Use __file__ with os.path.abspath() and os.path.dirname():
import os
script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)
print(script_path)
print(script_dir)
What each part does
__file__is the script filename/pathos.path.abspath(__file__)converts it to an absolute pathos.path.dirname(...)gets the folder containing the file
Example showing the difference
import os
print("Current working directory:", os.getcwd())
print(, os.path.dirname(os.path.abspath(__file__)))
Step by Step Execution
Consider this file:
import os
print("CWD:", os.getcwd())
print("SCRIPT DIR:", os.path.dirname(os.path.abspath(__file__)))
Assume:
- the script is stored at
/projects/tools/show_paths.py - you open a terminal in
/home/user - you run the script with:
python /projects/tools/show_paths.py
Step by step
- Python starts the process from
/home/user os.getcwd()checks the process working directory- It returns:
/home/user
__file__refers to the script being executedos.path.abspath(__file__)becomes:
/projects/tools/show_paths.py
os.path.dirname(...)removes the filename and returns:
Real World Use Cases
Loading files relative to where the user runs the program
If a command-line tool should use the caller's current location, use the working directory.
Examples:
- searching files in the folder the user is currently in
- writing output to the current terminal location
- batch-processing files in the current directory
Loading resources bundled with the script
If your script ships with files stored next to it, use the script directory.
Examples:
config.json- templates
- seed data
- local SQLite databases
Build and automation scripts
Automation tools often need both:
- the working directory to know where the command was launched
- the script directory to find helper files
Web and backend apps
Applications often build paths to:
- static files
- environment-specific configs
- migration files
- logs
Using explicit paths makes deployment more reliable.
Data processing
A data script may:
- read input files from the current directory
- load schemas or mappings from files stored with the code
Real Codebase Usage
In real projects, developers usually avoid relying on ambiguous relative paths.
Common pattern: build paths from the script location
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
config_file = BASE_DIR / "config.json"
This makes code more predictable because it does not depend on where the program was launched.
Common pattern: use the working directory for user input/output
from pathlib import Path
output_file = Path.cwd() / "report.txt"
This is useful when the output should appear in the user's current folder.
Validation pattern
Developers often check whether files exist before using them:
from pathlib import Path
config_path = Path(__file__).resolve().parent / "config.json"
if not config_path.exists():
raise FileNotFoundError(f"Missing config file: {config_path}")
Configuration pattern
Projects sometimes define a base path once and reuse it everywhere:
from pathlib Path
BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = BASE_DIR /
LOG_DIR = BASE_DIR /
Common Mistakes
1. Assuming relative paths are based on the script location
Broken example:
with open("config.json") as f:
data = f.read()
This only works if config.json is in the current working directory.
Safer version:
from pathlib import Path
config_path = Path(__file__).resolve().parent / "config.json"
with open(config_path) as f:
data = f.read()
2. Confusing os.getcwd() with the script directory
Broken assumption:
import os
script_dir = os.getcwd() # not necessarily true
os.getcwd() tells you where the process is running, not where the script file is stored.
3. Forgetting that __file__ may not exist in some interactive environments
In some environments such as an interactive shell or notebook, __file__ may be unavailable.
Comparisons
| Concept | What it means | Typical use |
|---|---|---|
os.getcwd() | Current working directory of the running process | User-relative input/output |
__file__ | Path of the current script file | Finding files stored with the script |
os.path.dirname(os.path.abspath(__file__)) | Directory containing the script | Loading bundled resources |
Path.cwd() | pathlib version of current working directory | Modern path handling |
Path(__file__).resolve().parent | pathlib version of script directory | Modern path handling |
vs
Cheat Sheet
import os
from pathlib import Path
Get current working directory
os.getcwd()
Path.cwd()
Get current script path
os.path.abspath(__file__)
Path(__file__).resolve()
Get current script directory
os.path.dirname(os.path.abspath(__file__))
Path(__file__).resolve().parent
Key rule
- Relative paths like
open("file.txt")use the current working directory - They do not automatically use the script directory
Safe way to open a file next to the script
from pathlib import Path
file_path = Path(__file__).resolve().parent / "file.txt"
with open(file_path) as f:
content = f.read()
Common edge case
__file__may not exist in interactive shells or notebooks
Good practice
FAQ
What is the difference between the current working directory and the script directory?
The current working directory is where the Python process is running. The script directory is where the .py file is stored. They can be different.
How do I get the current working directory in Python?
Use:
import os
os.getcwd()
or:
from pathlib import Path
Path.cwd()
How do I get the directory of the current Python file?
Use:
from pathlib import Path
Path(__file__).resolve().parent
Why does open("file.txt") sometimes fail?
Because Python looks for file.txt in the current working directory, not necessarily next to your script.
Is __file__ always available?
No. It usually exists in normal script execution, but not always in interactive environments like some shells or notebooks.
Should I use os.path or pathlib?
Mini Project
Description
Create a small Python script that prints both the current working directory and the script's own directory, then safely reads a text file stored next to the script. This demonstrates the difference between process location and file location in a practical way.
Goal
Build a script that shows both path types and loads a local file reliably, even when the script is run from another directory.
Requirements
- Print the current working directory
- Print the absolute path of the script directory
- Read a file named
message.txtlocated next to the script - Handle the case where
message.txtdoes not exist
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.