How to make python config file, in which relative paths are defined, but when scripts in other directories import config, paths are correct?
<p>I have the following directory structure for a program I'm writing in python: </p>

<pre><code>\code\
    main.py
    config.py
    \module_folder1\
        script1.1.py
\data\
    data_file1
    data_file2 
</code></pre>

<p>My <code>config.py</code> is a set of global variables that are set by the user, or generally fixed all the time. In particular <code>config.py</code> defines path variables to the 2 data files, something like <code>path1 = os.path.abspath("../data/data_file1")</code>. The primary use is to run <code>main.py</code> which imports <code>config</code> (and the other modules I wrote) and all is good. </p>

<p>But sometimes I need to run <code>script1.1.py</code> by itself. Ok, no problem. I can add to  <code>script1.1</code> the usual <code>if __name__ == '__main__':</code> and I can import <code>config</code>. But then I get <code>path1 = "../code/data/data_file1"</code> which doesn't exist. I thought that since the path is created in <code>config.py</code> the path would be relative to where <code>config.py</code> lives, but it's not. </p>

<p>So the question is, how can I have a central config file which defines relative paths, so I can import the config file to scripts in different directories and have the paths still be correct? </p>

<p>I should mention that the code repo will be shared among multiple machines, so hardcoding an absolute path is not an option.</p>

<p>(Not sure who posted this as a comment, then deleted it, but it seems to work so I'm posting as an answer.) The trick is to use <code>os.path.dirname(__file__)</code> in the config file, which gives the directory of the config file (<code>/code/</code>) regardless of where the script that imports config is. </p>

<p>Specifically to answer the question, in the config file define </p>

<pre><code>path1 = os.path.abspath(os.path.join(os.path.join(os.path.join( os.path.dirname(__file__) , '..'), 'data' ), 'data_file1' ) )
</code></pre>

python module relative-path