0

my structure is like this:

---file1.py

---file2.py

---directory1

  ---file3.py

---tools

  ---setting_manager.py

  ---settings.json

here directory1 and tools are two directories... In setting_manager.py, i have a function that read some settings from settings.json.

with open('settings.json', 'r') as f:
    properties = json.load(f)
    return properties

And in file1 file2 file3, I import the setting_manager like this:

from tools import setting_manager

but when I need to use this function in file1 file2 and file3. it seems python load funcs directly and can't find my 'settings.json'. For example, when using in file1, i need to set

with open('tools/settings.json', 'r') as f:

then it can work. but in file3 i need to set

with open('../tools/settings.json', 'r') as f:

is there any way to enable my demand?

1 Answer 1

2

I think you can define the dynamic path in your setting.py file as:

import sys, os

pathname = os.path.join(dir, '/relative/path/to/tools')

Then, You can use this global variable in any file in which you want to use base path.

Hope this will help.

Thanks.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, my 'setting_manager.py' and 'settings.json' are in the same directory called tools. and I want all my python files could import setting_manager and use its function. How should i do this and what's the 'dir' here?
dir is also global variable. You can set your directory path in this variable and can use it. You can set your global variable in 'setting.py' file and then use that variable in any file like "from setting import dir, pathname" and can use dir or path name in the file.
done. for your 'dir' : dir = os.path.dirname(os.path.abspath( __ file __ )).and filepath = os.path.join(dir,'settings.json')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.