Python
__file__ variable
programming
Python scripting
coding basics

what does the __file__ variable mean/do?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Python, __file__ tells a module where it was loaded from on disk. That sounds simple, but it is one of the most useful variables for building paths to configuration files, templates, or other resources that live next to your code.

What __file__ Contains

For a normal script or imported module, __file__ is a string path pointing to that file. It may be relative or absolute depending on how the interpreter started the program, so the first good habit is to normalize it.

python
1from pathlib import Path
2
3here = Path(__file__).resolve()
4print(here)
5print(here.parent)

here is the file itself. here.parent is the directory that contains it. In real code, the directory is usually what you want because that gives you a stable base for locating sibling files.

For example, imagine this layout:

  • 'app/main.py'
  • 'app/config.json'

You can load the config file safely like this:

python
1from pathlib import Path
2import json
3
4base_dir = Path(__file__).resolve().parent
5config_path = base_dir / "config.json"
6
7with config_path.open() as f:
8    config = json.load(f)
9
10print(config)

This approach is much safer than assuming the current working directory is the same as the script directory. The working directory can change depending on where the user ran the command from.

Why It Is Useful

The main value of __file__ is that it ties resource lookup to the module location instead of to the shell state. That matters in several common situations:

  1. command-line scripts started from different directories
  2. packages imported by test runners
  3. services started by process managers such as systemd
  4. tools executed inside containers

Without __file__, code often falls back to relative paths such as "./config.json". Those paths are relative to the current working directory, not to the source file. That is why they mysteriously break in production while seeming to work on a developer laptop.

__file__ Versus the Working Directory

A lot of confusion comes from mixing up __file__ with the current working directory. They answer different questions.

  • '__file__ asks: where is this module located?'
  • 'Path.cwd() asks: where was the process started from?'

Here is a small example that makes the difference visible:

python
1from pathlib import Path
2
3print("module path:", Path(__file__).resolve())
4print("working dir:", Path.cwd())

If you run the script from a parent folder, the two values will often be different. That difference is exactly why __file__ exists.

When __file__ Is Missing

__file__ is not guaranteed everywhere. In an interactive Python shell, a notebook, or some embedded execution environments, there may be no source file, so __file__ is undefined.

That means code like this can fail in a REPL:

python
from pathlib import Path
print(Path(__file__).resolve())

If you need code that works both in scripts and interactive environments, check first:

python
1from pathlib import Path
2
3if "__file__" in globals():
4    base_dir = Path(__file__).resolve().parent
5else:
6    base_dir = Path.cwd()
7
8print(base_dir)

This fallback is practical for demos and utilities. For production libraries, it is often better to use APIs designed for package data.

Modern Alternative for Package Resources

If your goal is to load files shipped with a package, importlib.resources is often a better tool than manually walking from __file__. It works cleanly with installed packages and avoids assumptions about the filesystem layout.

python
1from importlib.resources import files
2
3text = (files("my_package") / "data.txt").read_text()
4print(text)

That does not make __file__ obsolete. It just means __file__ is best for module-relative filesystem work, while importlib.resources is better for packaged resource access.

Common Pitfalls

The most common mistake is assuming __file__ is always absolute. Normalize it with Path(__file__).resolve() before using it.

Another mistake is using os.path.dirname(__file__) correctly but then joining it with a path that still depends on the working directory. Once you commit to module-relative paths, keep the whole chain module-relative.

A third pitfall is expecting __file__ to exist in notebooks or the interactive interpreter. It usually does not, so code intended for both environments needs a fallback or a different resource-loading strategy.

Summary

  • '__file__ is the path of the current module or script.'
  • Use Path(__file__).resolve().parent to build stable paths to nearby files.
  • '__file__ is different from the current working directory.'
  • It may be missing in notebooks, REPL sessions, or special execution environments.
  • For package data, importlib.resources is often the cleaner modern choice.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.