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>

<ol>
<li>You know the correct relative path to the file from the directory where <code>config.py</code> is located</li>
<li>You know the correct relative path to the directory where <code>config.py</code> is located (in your case, <code>..</code>)</li>
</ol>

<p>Both of this things are system-independent and do not change unless you change the structure of you project. Just add them together using <code>os.path.join('..', config.path_repative_to_config)</code></p>

python module relative-path