I have the following directory structure:
my_program/
foo.py
__init__.py # empty
conf/
config.cfg
__init__.py
you can use os
package in python for importing an absolute or relative path to the configuration file. Here is a working example with the relative path (we suppose that config.ini
in the folder name configuration
that is in the subdirectory of your python script folder):
import configparser
import os
path_current_directory = os.path.dirname(__file__)
path_config_file = os.path.join(path_current_directory, 'configuration', config.ini)
config = configparser.ConfigParser()
config.read(path_config_file)
Just load the path from a Variable and why so complex?
from configparser import ConfigParser
prsr=ConfigParser()
configfile="D:\Dummy\DummySubDir\Dummy.ini"
prsr.read(configfile)
print(prsr.sections())
Paths are relative to the current working directory, which is usually the directory from which you run your program (but the current directory can be changed by your program [or a module] and it is in general not the directory of your program file).
A solution consists in automatically calculating the path to your file, through the __file__
variable that the Python interpreter creates for you in foo.py
:
import os
config.read(os.path.join(os.path.dirname(__file__), 'conf', 'config.cfg'))
Explanation: The __file__
variable of each program (module) contains its path (possibly relative to the current directory when it was loaded, I guess—I could not find anything conclusive in the Python documentation—, which happens for instance when foo.py
is imported from its own directory).
This way, the import works correctly whatever the current working directory, and wherever you put your package.
PS: side note: __all__ = ["config.cfg"]
is not what you want: it tells Python what symbols (variables, functions) to import when you do from conf import *
. It should be deleted.
PPS: if the code changes the current working directory between the time the configuration-reading module is loaded and the time you read the configuration file, then you want to first store the absolute path of your configuration file (with os.path.abspath()
) before changing the current directory, so that the configuration is found even after the current directory change.