How do I stop file paths breaking when someone else runs my script?
Short answer
Build paths relative to the script's own location using __file__ and pathlib, rather than relying on the current working directory. Hard-coded absolute paths break for everyone but you.
The short version
Build paths relative to the script's own location with Path(__file__).parent, not relative to whatever directory the user happened to run from. Absolute paths pointing at your home directory break for everyone else, and bare relative paths break the moment someone runs the script from elsewhere.
The two things that break
df = pd.read_csv("/Users/me/projects/data/orders.csv") # works only on my machine
df = pd.read_csv("data/orders.csv") # works only from one directory
The first fails for every colleague. The second fails the moment the script is run from a parent folder, a scheduler, or an editor with a different working directory, which is why "it works for me" is such a common refrain.
The fix
from pathlib import Path
import pandas as pd
HERE = Path(__file__).resolve().parent
DATA = HERE.parent / "data"
df = pd.read_csv(DATA / "orders.csv")
__file__ is the path of the script itself, so HERE is where the script lives, regardless of where it was run from. Everything else is built relative to that, so the paths hold for anyone who checks out the project.
Why resolve()
resolve() turns the path into an absolute one and removes any .. segments, which makes it predictable and gives clearer error messages when something is missing.
Define paths in one place
Put the path constants at the top of a module, or in a small paths.py, so they are declared once rather than scattered.
# paths.py
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
OUTPUT = ROOT / "output"
Now every script imports from one place, and moving the project or renaming a folder means one edit rather than twenty.
Create output folders rather than assuming
OUTPUT.mkdir(parents=True, exist_ok=True)
df.to_csv(OUTPUT / "summary.csv", index=False)
Assuming a folder exists is the second most common path failure, and this one line removes it.
Notebooks are different
__file__ does not exist in a notebook, where the working directory is the notebook's folder. There, the cleanest solution is to install your project as a package (pip install -e .) and import a paths module from it, so the notebook and the scripts agree on where everything lives.
Configuration for real deployments
For paths that genuinely vary by environment (a data directory that differs between your laptop and a server), read them from an environment variable with a sensible default, rather than hard-coding either.
import os
DATA = Path(os.environ.get("DATA_DIR", ROOT / "data"))
This keeps the script portable while allowing the environment to override it, which is the pattern deployment tools expect.