My work dir like below:
base---
|--- dir1
| |---test2.py
|--- public.py
|--- config.json
|--- test1.py
In public.py, I coded like below:
def getCfg(key):
with open("config.json", 'r',encoding='utf-8') as f:
cfg=json.load(f)
return cfg[key]
In test1.py, I import public.py and invoke getCfg method,it’s ok
import public
public.getCfg("my_key")
and in test2.py, I import public.py and invoke getCfg method
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)
import public
public.getCfg("my_key")
system report error:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
I think it’s something wrong about work dir. How can I make it correct both in test1.py and test2.py?
My python version is 3.9. Thanks.
2
The problem you are facing is with the way you are getting the config.json
file you are telling python in both files test1.py
and test2.py
that your config.json
file is in the same directory where they are to fix this I would tell python to open the config.json file from this path path_base_project/config.json
:
def getCfg(key):
config_file_path = os.path.join(os.path.dirname(__file__),
'config.json')
with open(config_file_path , 'r',encoding='utf-8') as f:
cfg=json.load(f)
return cfg[key]
with this python will look for config.json
file in the base project and not the current file where the method getCfg()
is called