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

python

Solution

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.

Problem

I have the following directory structure: ``` my_program/ foo.py __init__.py # empty conf/ config.cfg __init__.py ``` In foo.py I have this: ``` import sys #sys.path.append('conf/') import ConfigParser config = ConfigParser.ConfigParser() config.read( 'conf/config.cfg' ) ``` In `conf/__init__.py` I have ``` __all__ = ["config.cfg"] ``` I get this error in `foo.py` that I can fix by giving the full path but not when I just put `conf/config.cfg` but I want the relative path to work: ``` ConfigParser.NoSectionError ``` which actually means that the file can't be loaded (so it can't read the section). I've tried commenting/un-commenting `sys.path.append('conf/')` in `foo.py` but it doesn't do anything. Any ideas?

Original source