Question

Get the Current File Directory Path in Python

pythondirectory

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(...).parent returns the parent directory as a Path object.

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:\python27 is the building or folder.
  • test.py is 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.

Take Quiz

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.json"

print(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:

  1. __file__ refers to the current module's filename or loading path, such as test.py or C:\python27\test.py.
  2. os.path.abspath(__file__) converts that value to an absolute file path:
    C:\python27\test.py
    
  3. os.path.dirname(...) removes the last path component, test.py.
  4. directory_path becomes:
    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.json file 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)
Take Quiz

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:

config_path = current_directory + "\\config.json"

It is easy to create missing or duplicate separators and is not portable. Prefer:

from pathlib import Path

config_path = Path(__file__).resolve().parent / "config.json"

Expecting __file__ everywhere

__file__ is normally available in imported modules and scripts loaded from files. It may not be defined in an interactive shell, some notebook environments, or code executed with exec(). If it is unavailable, choose a location appropriate to that environment, often Path.cwd().

Requiring a trailing separator

Do not assume a directory string must end in \ or /. A directory path without a trailing separator is valid and works correctly with path APIs.

Comparisons

ApproachWhat it representsBest use
os.path.abspath(__file__)Absolute path to the current fileWhen you need the filename and directory together
os.path.dirname(os.path.abspath(__file__))Directory containing the current file, as a stringExisting code using os.path
Path(__file__).resolve().parentDirectory containing the current file, as a Path objectNew Python code and path construction
os.getcwd() / Path.cwd()Current working directory of the running processFiles intentionally relative to where the command was launched

os.path works with strings and is widely used, including in older Python code. pathlib provides path objects, readable operations such as / for joining, and convenient methods such as .is_file() and .read_text().

For Python 2.7 specifically, use os.path; pathlib became part of Python's standard library in Python 3.4.

Take Quiz

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(...) or resolve(): 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.

Does Path(__file__).parent always produce an absolute path?

No. If __file__ is relative, .parent can also be relative. Use Path(__file__).resolve().parent when you need an absolute directory.

Why is __file__ not defined in my notebook or Python shell?

Interactive environments do not necessarily run code from a physical Python file. Use Path.cwd() if the working directory is the location you intend to use, or explicitly configure a base path.

Can I use this to locate files inside an installed package?

It can work for ordinary package files, but package-resource APIs are often better for distributable package data. For a simple script and files stored beside it, the __file__ approach is appropriate.

Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more