Python
file-handling
relative-path
coding-help
programming-duplicate

Open file in a relative location in Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Opening a file with a relative path in Python is easy, but the meaning of "relative" is where people get tripped up. A path can be relative to the current working directory of the running process, or relative to the script file on disk, and those are not the same thing.

Relative to the current working directory

Python's built-in open() resolves a plain relative path from the process working directory.

python
1with open("data/input.txt", "r", encoding="utf-8") as f:
2    text = f.read()
3
4print(text)

This works if the program is launched from a directory where data/input.txt exists relative to the current shell location. It fails if the same script is launched from somewhere else.

That is why code that seems fine in an IDE can break in tests, cron jobs, containers, or another developer's machine.

Relative to the script file

If the file lives inside your project next to the script or package, build the path from __file__ instead. pathlib is the cleanest modern way to do that.

python
1from pathlib import Path
2
3BASE_DIR = Path(__file__).resolve().parent
4file_path = BASE_DIR / "data" / "input.txt"
5
6with file_path.open("r", encoding="utf-8") as f:
7    text = f.read()
8
9print(text)

This version is robust because it does not care where the process was started. It anchors the path to the location of the script itself.

Decide which one you actually want

There is no universal best answer. Use the working-directory approach when the user is expected to run the program from a project root or pass paths relative to the current session. Use the __file__ approach when the file is part of the codebase and should always be found relative to the module.

That distinction is the important design point. Most "relative path" bugs come from mixing those two intentions without noticing.

Prefer pathlib for clarity

os.path still works, but pathlib.Path usually reads more clearly and composes better.

python
1from pathlib import Path
2
3project_root = Path(__file__).resolve().parent.parent
4config_path = project_root / "config" / "settings.json"
5
6with config_path.open("r", encoding="utf-8") as f:
7    config = f.read()

This is easier to read than string concatenation, and it is portable across operating systems.

Handle missing files explicitly

A relative path problem often shows up as FileNotFoundError. That should usually be handled close to the open call, especially when the file location is user-controlled or environment-dependent.

python
1from pathlib import Path
2
3path = Path("data/input.txt")
4if not path.exists():
5    raise FileNotFoundError(f"Missing file: {path.resolve()}")

A clear error beats silently assuming the wrong directory and debugging later.

Packaged data versus ad hoc files

If the file is part of an installed Python package rather than just a loose project directory, direct path building may not be the best interface. In that case, package-resource tools are often safer because the file might not live on disk in the same shape as your source tree. Relative path code is best for ordinary project files, scripts, and local tooling.

Common Pitfalls

  • Assuming open("file.txt") is relative to the script file rather than the current working directory.
  • Building paths with string concatenation instead of pathlib or proper path utilities.
  • Writing code that only works when launched from one specific directory.
  • Ignoring FileNotFoundError and making path bugs harder to diagnose.
  • Using __file__ for user-supplied paths that should really be resolved from the current execution context.

Summary

  • Plain relative paths in open() are resolved from the current working directory.
  • Files bundled with your script are often better addressed relative to __file__.
  • 'pathlib.Path is the cleanest way to build relative paths in modern Python.'
  • Decide whether the path should follow the process location or the script location.
  • Most relative-path bugs are really about choosing the wrong reference point.

Course illustration
Course illustration

All Rights Reserved.