0

I have the following project structure:

SmartMirror/
|--config.json
|--main.py
|--widgets/
    |--weather/
        |--__init__.py
        |--weather.py
    |--calendar/
        |--__init__.py
        |--calendar.py

I want to access the config.json file from every widget python file.

What I do right now is use the following line

CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath("config.json")), "config.json")

which works when I run main.py from the SmartMirror directory but if I directly run the weather.py from a different folder it (understandably) can't locate the config.json file.

I was wondering if there is a better and safer way to access the config file from every widget or any other python module I add in the future.

z3y50n
  • 51
  • 1
  • 8
  • Does this answer your question? [How to read a (static) file from inside a Python package?](https://stackoverflow.com/questions/6028000/how-to-read-a-static-file-from-inside-a-python-package) – Tomerikoo Dec 28 '20 at 13:14
  • Not really since my SmartMirror folder is not a package and I want to read the config.json from weather.py which is some files deeper and not the other way around. – z3y50n Dec 28 '20 at 13:34
  • Then why not just use the absolute path of the file? – Tomerikoo Dec 28 '20 at 13:37
  • Well that is what I am doing but I am wondering if there is a more robust and safer way – z3y50n Dec 28 '20 at 14:07

1 Answers1

0

Now one safer way I found that works is to write os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "config.json")

Also a better way to avoid the use of all these dirname can be found in this answer

z3y50n
  • 51
  • 1
  • 8