Reputation: 8418
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.
Upvotes: 1
Views: 5981
Reputation: 8418
(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 os.path.dirname(__file__)
in the config file, which gives the directory of the config file (/code/
) regardless of where the script that imports config is.
Specifically to answer the question, in the config file define
path1 = os.path.abspath(os.path.join(os.path.join(os.path.join( os.path.dirname(__file__) , '..'), 'data' ), 'data_file1' ) )
Upvotes: 0
Reputation: 3194
config.py
is locatedconfig.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)
Upvotes: 1