travelingbones
travelingbones

Reputation: 8418

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.

Upvotes: 1

Views: 5981

Answers (2)

travelingbones
travelingbones

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

Dmitry Torba
Dmitry Torba

Reputation: 3194

  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)

Upvotes: 1

Related Questions