travelingbones travelingbones - 1 month ago 6x
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:


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

But sometimes I need to run
by itself. Ok, no problem. I can add to
the usual
if __name__ == '__main__':
and I can import
. But then I get
path1 = "../code/data/data_file1"
which doesn't exist. I thought that since the path is created in
the path would be relative to where
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.

  1. You know the correct relative path to the file from the directory where is located
  2. You know the correct relative path to the directory where 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)