travelingbones travelingbones - 3 months ago 9
Python Question

How to make python config file, in which relative paths are defined, but when scripts in other directories import config, paths are correct?

I have the following directory structure for a program I'm writing in python:

\code\
main.py
config.py
\module_folder1\
script1.1.py
\data\
data_file1
data_file2


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

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

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?

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

Answer
  1. You know the correct relative path to the file from the directory where config.py is located
  2. You know the correct relative path to the directory where config.py is located (in your case, ..)

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

Comments