Question
How can I get the directory path containing the Python file that is currently executing?
For example:
import os
print(os.path.abspath(__file__))
# C:\\python27\\test.py
I want the containing directory instead:
C:\python27\\
Short Answer
You will learn the difference between a file path and a directory path, how __file__ identifies the current module, and how to reliably obtain the directory containing a Python script using both os.path and pathlib.
Concept
A path is a string or path object that identifies a location in a file system.
- A file path includes a filename, such as
C:\python27\test.py. - A directory path identifies the folder that contains the file, such as
C:\python27.
In a Python file that was loaded from disk, __file__ contains the path used to load that module. It may be relative, so convert it to an absolute path before depending on it.
To obtain the containing folder, use a path operation:
os.path.dirname(...)returns the directory portion of a path string.pathlib.Path(...).parentreturns the parent directory as aPathobject.
This matters because code often needs to load files stored next to the script: configuration files, templates, sample data, SQL files, or other application resources. Building paths from the script location is usually more reliable than building them from the process's current working directory.
Mental Model
Think of a file path as a mailing address:
C:\python27\test.py
C:\python27is the building or folder.test.pyis the specific room or file.
__file__ gives you the full address of the current Python file. dirname or parent removes the final file name and leaves the folder address.
Syntax and Examples
With os.path:
import os
file_path = os.path.abspath(__file__)
current_directory = os.path.dirname(file_path)
print(current_directory)
os.path.abspath(__file__) creates an absolute path to the current file. Then os.path.dirname(...) returns the part before the final filename.
A compact version is:
import os
current_directory = os.path.dirname(os.path.abspath(__file__))
With modern Python, pathlib is often easier to read:
from pathlib import Path
current_directory = Path(__file__).resolve().parent
print(current_directory)
Path(__file__) creates a path object, resolve() makes it absolute, and .parent selects the directory that contains the file.
To build a path to a neighboring file, do not concatenate strings manually:
from pathlib import Path
base_directory = Path(__file__).resolve().parent
config_path = base_directory /
(config_path)
Step by Step Execution
Consider this file located at C:\python27\test.py:
import os
absolute_file_path = os.path.abspath(__file__)
directory_path = os.path.dirname(absolute_file_path)
print(absolute_file_path)
print(directory_path)
Execution proceeds as follows:
__file__refers to the current module's filename or loading path, such astest.pyorC:\python27\test.py.os.path.abspath(__file__)converts that value to an absolute file path:C:\python27\test.pyos.path.dirname(...)removes the last path component,test.py.directory_pathbecomes:C:\python27
The result may not include a trailing slash. That is normal: C:\python27 already identifies the directory. Path-joining functions handle separators correctly.
Real World Use Cases
Common reasons to find the current file's directory include:
- Configuration loading: Read a
settings.jsonfile shipped beside an application module. - Templates and static files: Locate HTML templates, email templates, images, or bundled CSS files.
- Data-processing scripts: Open an input CSV located relative to the script rather than relative to the terminal's folder.
- Database setup: Load a SQL schema file stored in the project.
- Command-line tools: Find package resources regardless of where the user runs the command.
Example: loading a JSON file next to a script:
import json
from pathlib import Path
base_directory = Path(__file__).resolve().parent
settings_file = base_directory / "settings.json"
with settings_file.open(encoding="utf-8") as file:
settings = json.load(file)
Real Codebase Usage
In real projects, developers usually calculate a module's base directory once and use safe joining operations afterward.
A common pathlib pattern is:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
TEMPLATE_DIR = BASE_DIR / "templates"
DEFAULT_CONFIG = BASE_DIR / "config" / "default.json"
For a file nested inside a package, multiple .parent calls can reach a project-level directory:
from pathlib import Path
# If this file is project/app/routes/users.py:
PROJECT_ROOT = Path(__file__).resolve().parents[2]
Use this deliberately. A path based on __file__ is appropriate for files packaged with code. User-provided files, uploads, cache files, and logs often belong in configurable locations instead.
When validating a required resource, use a guard clause and a useful error:
from pathlib import Path
config_path = Path(__file__).resolve().parent / "config.json"
if not config_path.is_file():
raise FileNotFoundError(f"Required configuration file not found: {config_path}")
Common Mistakes
Using abspath(__file__) without removing the filename
This returns the full file path, not its directory:
import os
path = os.path.abspath(__file__)
# C:\python27\test.py
Fix it with dirname:
path = os.path.dirname(os.path.abspath(__file__))
Confusing the current working directory with the script directory
import os
print(os.getcwd())
os.getcwd() returns the folder from which the Python process was started. It can differ from the folder containing your script.
For example, a user can run:
C:\> python C:\projects\tool\main.py
Here, os.getcwd() may be C:\, while Path(__file__).resolve().parent is C:\projects\tool.
Joining paths with string concatenation
Avoid:
Comparisons
| Approach | What it represents | Best use |
|---|---|---|
os.path.abspath(__file__) | Absolute path to the current file | When you need the filename and directory together |
os.path.dirname(os.path.abspath(__file__)) | Directory containing the current file, as a string | Existing code using os.path |
Path(__file__).resolve().parent | Directory containing the current file, as a Path object | New Python code and path construction |
os.getcwd() / Path.cwd() | Current working directory of the running process | Files intentionally relative to where the command was launched |
os.path works with strings and is widely used, including in older Python code. provides path objects, readable operations such as for joining, and convenient methods such as and .
Cheat Sheet
# Python 2.7-compatible: current file's directory as a string
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
# Modern Python: current file's directory as a Path object
from pathlib import Path
base_dir = Path(__file__).resolve().parent
# Build a path to a file beside the current script
config_path = base_dir / "config.json" # pathlib
# os.path equivalent
config_path = os.path.join(base_dir, "config.json")
__file__: path used to load the current module.abspath(...)orresolve(): makes the path absolute.dirname(...)or.parent: gets the containing directory.getcwd()/Path.cwd(): gets the launch directory, not necessarily the script directory.- A trailing slash is not required for a directory path.
__file__may be unavailable in interactive environments.
FAQ
How do I get the directory of the current Python file?
Use:
import os
current_directory = os.path.dirname(os.path.abspath(__file__))
Or, in modern Python:
from pathlib import Path
current_directory = Path(__file__).resolve().parent
What is the difference between __file__ and os.getcwd()?
__file__ identifies the current Python module's file. os.getcwd() identifies the process's current working directory, which depends on where the command was launched.
Why does dirname not return a trailing slash?
A trailing slash is optional. The returned value is still a valid directory path. Use path-joining APIs instead of adding separators yourself.
Should I use os.path or pathlib?
Use pathlib for new Python 3 code because it is readable and provides useful path methods. Use os.path when supporting Python 2.7 or working within an existing os.path codebase.
Mini Project
Description
Create a small script that reads a text file stored beside the script itself. This demonstrates why using the script directory is safer than relying on the directory from which a user launches the command.
Goal
Print the contents of a message.txt file located in the same directory as the Python script.
Requirements
Create a file named message.txt in the same folder as the script.
Use the directory of the current script to construct the file path.
Do not build file paths with string concatenation.
Display a clear message if message.txt does 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.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.