I have the following project structure
SampleProject
com
python
example
source
utils
ConfigManager.py
conf
constants.cfg
How to access constants.cfg from ConfigManager.py.
I have a limitation
- I can not give full path(absolute path) of constants.cfg because if I run in different PC it should work with out any modification
Also if I represent something like below, I can access the file. But I don't want to give back slash every time
filename = ..\\..\\..\\..\\..\\..\\constants.cfg`
Currently I am doing something like this. But this works only when constants.cfg and ConfigManager.py are in same directory
currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
file = open(os.path.join(currentDir,'constants.cfg'))
If you had some module in the root of the project tree, say config_loader.py that looked like this:
And then in ConfigManager.py or any other module that needs the configs:
You could even have your config_loader.py just return the config file.
You can use the pathlib package in Python 3.0+
This gets the path to any file contained in the SampleProject folder across different platforms.
Then simply call the function with the file_path as an argument:
And then the usual procedure:
If
conf
is a Python package then you could usepkgutil.get_data()
:Or if
setuptools
is installed –pkg_resources.resource_string()
:If
constants.cfg
is not in a package then pass its path as a command-line parameter, or set it in an environment variable e.g.,CONFIG_MANAGER_CONSTANTS_PATH
, or read from a fixed set of default paths e.g.,os.path.expanduser("~/.config/ConfigManager/constants.cfg")
. To find a place where to put user data, you could useappdirs
module.You can't use
os.getcwd()
that returns current working directory if you may runConfigManager.py
from different directories. Relative path"../../..."
won't work for the same reason.If you are certain that the relative position of
ConfigManager.py
andconstants.cfg
in the filesystem won't change: