6

I have a module that needs to initialize some settings by reading a config file. The directory structure looks something like this:

root\
    config\
        conf.cfg
    src\
        module1.py

I'm fine when I set the relative path to ../config/conf.cfg and run the module in its current directory. But when I import the module somewhere else and run it in another directory I run into problems.

How should I set the path so the module always looks in the same relative location (eg one directory up from where the module is located) and how do I ensure this works for other people that download my repo (who may not have root in the same place)?

R__raki__
  • 847
  • 4
  • 15
  • 30
drbeans345
  • 63
  • 1
  • 4
  • One way would be to make all paths absolute from the installation root folder and start everything from there. – sobek Nov 10 '16 at 19:47
  • How do I set the root folder path? env variable? – drbeans345 Nov 10 '16 at 19:53
  • What is `root\` in your example? Is the config file not part of your project? – sobek Nov 10 '16 at 20:01
  • root is the root directory of my git repo. The config file is part of the project. – drbeans345 Nov 10 '16 at 20:08
  • Then you would define the config path as config/conf.cfg in the module, cd into root and start module by doing python src/module1.py. Depending on what os you are on, this link might also be helpful. http://stackoverflow.com/questions/2860153/how-do-i-get-the-parent-directory-in-python – sobek Nov 10 '16 at 20:23
  • Thanks. I'll do that then. – drbeans345 Nov 10 '16 at 20:29

1 Answers1

3
os.path.realpath(__file__) 

will give you the path of the current file, resolving any symlinks in the path. This works fine on my machine.

Manuel Taber
  • 427
  • 5
  • 19