0

Example Project:

|- main.py 
|- Module
    |- __init__.py
    |- worker.py
    |- worker_config.json

main.py

from Module import worker
#do stuff ...

worker.py

import json
mySettings = json.load(open("worker_config.json", "r"))
#more stuff ...

Running worker.py on it's own works. Importing worker.py from main.py works basically also. But when worker.py is imported by main.py, the worker_config.json file can't be accessed, because the path has now changed to the main folder.

Is there a way to fix the path for the worker_config file when the module is imported and still ensure that the file can be accessed when worker.py is directly executed?

chrisg
  • 85
  • 8

2 Answers2

1

Something like:

import json
import os

configfile_path = os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        "config.json"
)
json.load(open(configfile_path, "r"))

Should do the trick

yayg
  • 309
  • 2
  • 12
0

You can change your code to

import json
mySettings = json.load(open("../worker_config.json", "r"))
#more stuff ...
bapap
  • 514
  • 8
  • 25