The error is purely about “where Python is looking” vs. “where the file really is”.
When you open a file with a relative path (e.g. open('config/application.conf')), Python starts from the current working directory (CWD), not from the directory that holds the script.
Your layout (simplified)
project/ ← project root (CWD is often not here when you double-click/run)
├── folder1/
│ └── script1.py ← you run this
└── folder2/
├── config/
│ └── application.conf
└── script2.py
Because script1 lives in folder1, the CWD is usually project/folder1, so Python searches for
project/folder1/config/application.conf – which of course is missing.
Below are three common fixes; pick the one that feels right for your project.
──────────────────
1️⃣ Build the path from the script location (recommended)
──────────────────
Use pathlib to walk “up” to project/ and then “down” to the config file:
# script1.py (folder1)
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent # …/project
cfg_path = ROOT / 'folder2' / 'config' / 'application.conf'
with cfg_path.open() as f:
data = f.read()
print(data)
Key points
• Path(file).resolve() → absolute path of this script
• .parent.parent → go up two levels (folder1 → project)
• Then append folder2/config/application.conf
──────────────────
2️⃣ Treat folder2 as a Python package & use importlib.resources
──────────────────
If folder2 has an init.py you can do:
# script1.py
import importlib.resources as res
with res.files('folder2.config').joinpath('application.conf').open() as f:
data = f.read()
Advantage: works regardless of CWD; deploys well inside wheels/zipapps.
──────────────────
3️⃣ Run the script from the project root (changes CWD)
──────────────────
Instead of
cd project/folder1
python script1.py
run
cd project
python -m folder1.script1 # module execution keeps CWD at project/
Now relative path 'folder2/config/application.conf' will succeed.
──────────────────
Extra tips
──────────────────
• Never hard-code OS-specific separators ('\' or '/') – let pathlib do it.
• If you rely on environment variables (.env), load them with python-dotenv:
from dotenv import load_dotenv
from pathlib import Path
load_dotenv(Path(__file__).resolve().parent.parent / '.env')
• If your config is short, consider putting it in .env instead and read via os.getenv.
Choose one approach, apply it consistently, and FileNotFoundError will be gone 🚀