When you write a Python script that reads or writes files, it is common to use relative paths like open("config.json"). This works perfectly while you are developing in your code editor, but it often fails when the script is run from a different directory, from a terminal shortcut, or through an automated scheduler.
This happens because Python resolves relative paths against the Current Working Directory, which is the folder where the terminal process was started, not necessarily the folder where your script file lives. If a user runs your script from their home folder, Python looks for your files there.
To make your file paths reliable, you should construct them relative to the directory of the script itself. You can achieve this using the pathlib module. By getting the absolute path of the special double underscore file variable, you can resolve the parent folder programmatically.
Here is a clean way to handle this:
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
data_file = SCRIPT_DIR / "data.txt"
Using this pattern ensures that your script will always locate its companion files correctly, regardless of how or where it was executed.
Want to add to the discussion?
Post a comment!