Load Python Script Assets Independently of the Working Directory

A small release tool reads a template stored beside its source file. It works when launched from its own folder, then fails in a scheduled job that starts elsewhere. The file still exists; the program has assumed that its working directory and source directory are the same.

These examples use Python 3.10 or later and ordinary scripts stored on disk. The goal is a precise path contract: the default template belongs to the tool, while an explicitly supplied template path belongs to the caller.

Identify Which Directory Owns the File

Path("assets") / "header.txt" is relative. Opening it uses the process’s current working directory at the time of the operation. An IDE, shell, or scheduler can choose a different starting directory without moving the script.

Path.cwd() reports that directory. It does not locate the executing source file. The pathlib reference documents this distinction through its directory and path operations.

Use a layout like this:

1
2
3
4
5
release_tool/
    show_header.py
    assets/
        header.txt
    test_header.py

Put the single line Release notes in assets/header.txt, followed by a newline. This is a tool-owned default, so launching from another directory should still read that same file. A caller’s explicit input file will use a different rule.

Anchor the Default to the Source File

Save this complete script as show_header.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from pathlib import Path
import sys


BASE_DIR = Path(__file__).resolve().parent
DEFAULT_HEADER = BASE_DIR / "assets" / "header.txt"


def read_header(path=None):
    selected = DEFAULT_HEADER if path is None else Path(path)
    return selected.read_text(encoding="utf-8")


if __name__ == "__main__":
    if len(sys.argv) > 2:
        raise SystemExit("usage: show_header.py [template-path]")
    selected = sys.argv[1] if len(sys.argv) == 2 else None
    print(read_header(selected), end="")

For this disk-based script, __file__ identifies its source path. Resolve it before taking the parent so the stored default is absolute. resolve() also follows symbolic links: a symlinked launcher therefore finds assets beside the resolved source, rather than beside the link. The resolve documentation specifies that behavior.

Building an absolute path does not prove that the asset exists. The actual read still raises an exception for a missing file, a directory in its place, invalid UTF-8, or insufficient permissions. Letting that exception surface is useful for a small command-line tool whose installation is incomplete.

Preserve Caller-Relative Overrides

Run python show_header.py from the tool directory to print the bundled header. Supply python show_header.py custom.txt to read a file relative to the launching directory instead.

The None check makes this policy explicit. An empty string is an explicit path value, not a request for the default; Path("") names the current directory, so attempting to read it as a text file fails. A truthiness fallback such as path or DEFAULT_HEADER would hide that distinction.

Avoid changing the process directory to make the default work. That also changes the meaning of every later relative path in the process, including paths used by other modules. Passing the selected path directly keeps each operation’s meaning visible.

This example does not expand ~ or environment variables inside the supplied string. Shell processing may occur before Python starts, but the Python helper itself treats its argument as a filesystem path without additional interpolation.

Test from Unrelated Working Directories

Save this as test_header.py beside the script. Run python test_header.py after creating the default asset described above:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory


script = Path(__file__).resolve().with_name("show_header.py")


def invoke(cwd, *args):
    return subprocess.run(
        [sys.executable, str(script), *args],
        cwd=cwd,
        check=True,
        capture_output=True,
        text=True,
        encoding="utf-8",
    ).stdout


with TemporaryDirectory() as folder:
    root = Path(folder)
    first = root / "first"
    second = root / "second"
    first.mkdir()
    second.mkdir()
    for directory in (first, second):
        (directory / "assets").mkdir()
        (directory / "assets" / "header.txt").write_text(
            "Wrong default\n", encoding="utf-8"
        )
    (first / "custom.txt").write_text("First override\n", encoding="utf-8")
    (second / "custom.txt").write_text("Second override\n", encoding="utf-8")

    assert invoke(first) == "Release notes\n"
    assert invoke(second) == "Release notes\n"
    assert invoke(first, "custom.txt") == "First override\n"
    assert invoke(second, "custom.txt") == "Second override\n"
    assert invoke(second, str(first / "custom.txt")) == "First override\n"

print("Script asset path checks passed.")

The decoy default files make an accidental working-directory lookup fail visibly. Distinct override contents prove that relative arguments still follow the caller’s directory. Separate child processes exercise real launch behavior without changing the test process’s directory.

Keep the Disk-Based Assumption Visible

This pattern fits a standalone script distributed together with its adjacent assets. It assumes the source and asset are available as ordinary filesystem files. Interactive sessions and notebooks may not define __file__; custom importers and packaged applications can have different resource layouts.

For data shipped inside an importable package, consider importlib.resources , whose resource API supports storage that need not correspond to a physical package directory. Do not guess a package’s installation path by climbing a fixed number of parents.

Likewise, keep writable output locations separate from the source directory: an installed tool may have read-only assets. Choose output paths through an explicit argument or application policy. The useful rule is to decide who owns each path before selecting its base directory.