Can't load relative config file using ConfigParser from sub-directory

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.

Tags:

Python