Finding Files Next to a Module

Dev’s digest reads its three plants from boiler/plants.json, and it must find that file wherever you start it from. You’ll anchor the path to the module, then replace the reading code with a JSON import.

Anchor the Path With import.meta

Python’s settings.py builds the path from its own __file__, so the shell’s current folder doesn’t matter:

Language: Python
import json
from pathlib import Path

PLANTS_FILE = Path(__file__).with_name("plants.json")

def load_plants():
    return json.loads(PLANTS_FILE.read_text(encoding="utf-8"))

It reads this plant list, saved beside it as boiler/plants.json:

Language: JSON Filename: plants.json
[
  {
    "name": "Main boiler",
    "log": "main.log",
    "controller": "halden",
    "limit": 75
  },
  {
    "name": "Sports hall",
    "log": "sports-hall.log",
    "controller": "halden",
    "limit": 80
  },
  {
    "name": "Science block",
    "log": "science.log",
    "controller": "ostra",
    "limit": 55
  }
]

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.